How can i use xaxis_date() with barh()?

后端 未结 1 1713
無奈伤痛
無奈伤痛 2020-12-17 23:53

in the code below, bdate and edate are both datetime.datetime() objects:

pylab.barh(ypos, edate - bdate, left=bdate, height=TRMWidth )

but

相关标签:
1条回答
  • 2020-12-18 00:03

    What's happening is that matplotlib doesn't actually use datetime objects for plotting.

    Dates are first converted into an internal floating point format. The conversion isn't set up to handle timedeltas (which is arguably an oversight).

    You can basically do exactly what you wanted, you just need to explictly convert the dates to matplotlib's internal format first, and then call ax.xaxis_date().

    As a quick example (Most of this is generating data to plot...):

    import datetime as dt
    import matplotlib.pyplot as plt
    import matplotlib.dates as mdates
    
    def drange(start, end, interval=dt.timedelta(days=1)):
        output = []
        while start <= end:
            output.append(start)
            start += interval
        return output
    
    # Generate a series of dates for plotting...
    edate = drange(dt.datetime(2012, 2, 1), dt.datetime(2012, 6, 15), 
                          dt.timedelta(days=5))
    bdate = drange(dt.datetime(2012, 1, 1), dt.datetime(2012, 5, 15), 
                          dt.timedelta(days=5))
    
    # Now convert them to matplotlib's internal format...
    edate, bdate = [mdates.date2num(item) for item in (edate, bdate)]
    
    ypos = range(len(edate))
    fig, ax = plt.subplots()
    
    # Plot the data
    ax.barh(ypos, edate - bdate, left=bdate, height=0.8, align='center')
    ax.axis('tight')
    
    # We need to tell matplotlib that these are dates...
    ax.xaxis_date()
    
    plt.show()
    

    enter image description here

    0 讨论(0)
提交回复
热议问题