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

前端 未结 3 769
时光取名叫无心
时光取名叫无心 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:32

    The example from @Pelson, simplified.

    import matplotlib.pyplot as plt
    import datetime as dt
    
    #Two subplots that share one x axis
    fig,ax=plt.subplots(2,sharex=True)
    
    #plot data
    n_pts = 10
    dates = [dt.datetime.now() + dt.timedelta(days=i) for i in range(n_pts)]
    ax[0].bar(dates, range(10, 20))
    ax[1].plot(dates, range(10))
    
    #rotate and format the dates on the x axis
    fig.autofmt_xdate()
    

    The subplots sharing an x-axis are created in one line, which is convenient when you want more than two subplots:

    fig, ax = plt.subplots(number_of_subplots, sharex=True)
    

    To format the date correctly on the x axis, we can simply use fig.autofmt_xdate()

    For additional informations, see shared axis demo and date demo from the pylab examples. This example ran on Python3, matplotlib 1.5.1

提交回复
热议问题