Matplotlib: Adding an axes using the same arguments as a previous axes

前端 未结 5 2046
死守一世寂寞
死守一世寂寞 2020-11-27 17:22

I want to plot data, in two different subplots. After plotting, I want to go back to the first subplot and plot an additional dataset in it. However, when I do so I get this

5条回答
  •  一个人的身影
    2020-11-27 18:08

    The error appears when you create same axis object more then one time. In your example you first create two subplot objects (with method plt.subplot).

    type(plt.subplot(2, 1, 2)) Out: matplotlib.axes._subplots.AxesSubplot
    

    python automatically sets the last created axis as default. Axis means just the frame for the plot without data. That's why you can perform plt.plot(data). The method plot(data) print some data in your axis object. When you then try to print new data in the same plot you can't just use plt.subplot(2, 1, 2) again, because python try to create a new axis object by default. So what you have to do is: Assign each subplot to an variable.

    ax1 = plt.subplot(2,1,1)
    ax2 = plt.subplot(2,1,2)
    

    then choose your "frame" where you want to print data in:

    ax1.plot(data)
    ax2.plot(data+1)
    ax1.plot(data+2)
    

    If you are interested to plot more graphs (e.g. 5) in one figure, just create first a figure. Your data is stored in a Pandas DataFrame and you create for each column a new axis element in a list. then you loop over the list and plot in each axis element the data and choose the attributes

    import pandas as pd 
    import matplotlib.pyplot as plt 
    
    #want to print all columns
    data = pd.DataFrame('some Datalist')
    plt.figure(1)
    axis_list = []
    
    #create all subplots in a list 
    for i in range(data.shape[1]):
    axis_list.append(plt.subplot(data.shape[1],1,i+1)
    
    for i,ax in enumerate(axis_list):
    
        # add some options to each subplot  
        ax.grid(True)
        #print into subplots
        ax.plot(data.iloc[:,[i]])
    

提交回复
热议问题