matplotlib: Creating two (stacked) subplots with SHARED X axis but SEPARATE Y axis values

前端 未结 3 810
时光取名叫无心
时光取名叫无心 2021-02-05 15:42

I am using matplotlib 1.2.x and Python 2.6.5 on Ubuntu 10.0.4. I am trying to create a SINGLE plot that consists of a top plot and a bottom plot.

The X axis is the date

3条回答
  •  半阙折子戏
    2021-02-05 16:16

    There seem to be a couple of problems with your code:

    1. If you were using figure.add_subplots with the full signature of subplot(nrows, ncols, plotNum) it may have been more apparent that your first plot asking for 1 row and 1 column and the second plot was asking for 2 rows and 1 column. Hence your first plot is filling the whole figure. Rather than fig.add_subplot(111) followed by fig.add_subplot(212) use fig.add_subplot(211) followed by fig.add_subplot(212).

    2. Sharing an axis should be done in the add_subplot command using sharex=first_axis_instance

    I have put together an example which you should be able to run:

    import matplotlib.pyplot as plt
    import matplotlib.ticker as mticker
    import matplotlib.dates as mdates
    
    
    import datetime as dt
    
    
    n_pts = 10
    dates = [dt.datetime.now() + dt.timedelta(days=i) for i in range(n_pts)]
    
    ax1 = plt.subplot(2, 1, 1)
    ax1.plot(dates, range(10))
    
    ax2 = plt.subplot(2, 1, 2, sharex=ax1)
    ax2.bar(dates, range(10, 20))
    
    # Now format the x axis. This *MUST* be done after all sharex commands are run.
    
    # put no more than 10 ticks on the date axis.  
    ax1.xaxis.set_major_locator(mticker.MaxNLocator(10))
    # format the date in our own way.
    ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
    
    # rotate the labels on both date axes
    for label in ax1.xaxis.get_ticklabels():
        label.set_rotation(30)
    for label in ax2.xaxis.get_ticklabels():
        label.set_rotation(30)
    
    # tweak the subplot spacing to fit the rotated labels correctly
    plt.subplots_adjust(hspace=0.35, bottom=0.125)
    
    plt.show()
    

    Hope that helps.

提交回复
热议问题