How to plot data against specific dates on the x-axis using matplotlib

前端 未结 1 1510
野趣味
野趣味 2020-11-30 05:03

I have a dataset consisting of date-value pairs. I want to plot them in a bar graph with the specific dates in the x-axis.

My problem is that matplotlib

相关标签:
1条回答
  • 2020-11-30 05:39

    What you're doing is simple enough that it's easiest to just using plot, rather than plot_date. plot_date is great for more complex cases, but setting up what you need can be easily accomplished without it.

    e.g., Based on your example above:

    import datetime as DT
    from matplotlib import pyplot as plt
    from matplotlib.dates import date2num
    
    data = [(DT.datetime.strptime('2010-02-05', "%Y-%m-%d"), 123),
            (DT.datetime.strptime('2010-02-19', "%Y-%m-%d"), 678),
            (DT.datetime.strptime('2010-03-05', "%Y-%m-%d"), 987),
            (DT.datetime.strptime('2010-03-19', "%Y-%m-%d"), 345)]
    
    x = [date2num(date) for (date, value) in data]
    y = [value for (date, value) in data]
    
    fig = plt.figure()
    
    graph = fig.add_subplot(111)
    
    # Plot the data as a red line with round markers
    graph.plot(x,y,'r-o')
    
    # Set the xtick locations to correspond to just the dates you entered.
    graph.set_xticks(x)
    
    # Set the xtick labels to correspond to just the dates you entered.
    graph.set_xticklabels(
            [date.strftime("%Y-%m-%d") for (date, value) in data]
            )
    
    plt.show()
    

    If you'd prefer a bar plot, just use plt.bar(). To understand how to set the line and marker styles, see plt.plot() Plot with date labels at marker locations http://www.geology.wisc.edu/~jkington/matplotlib_date_labels.png

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