plt.setp alternative for subplots or how to set text rotation on x axis for subplot

前端 未结 1 1817
忘了有多久
忘了有多久 2021-01-14 08:55

I have this code in which I am able to control attributes like: range of x axis, title, xlabel, ylabel, legend, grid, rotation of text on x labels:

#!/usr/bi         


        
相关标签:
1条回答
  • 2021-01-14 09:18

    I will try to answer your questions 1 by 1. But before, you need to understand that there is no difference between a plot and a subplot. Whereas plot usually refers to a single axes in a figure, subplots refer to one of multiple axes in a figure. But to matplotlib they are both axes instances.

    plt usually refers to the pyplot module (if imported as import matplotlib.pyplot as plt). This module has many functions, such as the ones you listed and also many plotting functions (e.g., plot, scatter, etc.). However, these are just for convenience and call the corresponding functions on the current axes instance. In a very simplified manner plt.plot is built up like this:

    def plot(*args, **kwargs):
        ax = plt.gca()
        return ax.plot(*args, **kwargs)
    

    Unfortunately, the naming is not consistent. But in general the axes method uses set_* and get_*, whereas the plt functions don't.

    This means that you could create the first plot that you have posted, with using fig, ax = plt.subplots(1) and then continue to use the axes methods: ax.plot(...), etc.

    As to your questions:

    1. I don't think so. But as a general advise, I would try to use the axes methods, as they offer all the functionality, whereas the plt equivalents are limited.
    2. matplotlib was inspired by the plotting functionality of Matlab. Thats where the plt functionality comes from.
    3. I'm not sure if there is a gerenal approach to this. Usually things can be guessed by the names (e.g. plt.title --> ax.set_title). Using matplotlib usually also means to have the documentation at hand.
    4. Again, by experience or by name. But you don't have to. You can also just use one!
    5. plt.setp is a helper function. It sets a property (hence its name) for a list of artists. Thus plt.setp(labels, rotation=45) does something like:

      for i in labels:
          i.set_rotation(45)
      

      The question is just how you get the reference to the list of labels. you can either get them via:

      labels = plt.xticklabels()
      

      or

      labels = ax.get_xticklabels()
      
    0 讨论(0)
提交回复
热议问题