【问题标题】:Plotting a graph on matplotlib with dates on x axis only shows some of the dates在 matplotlib 上绘制带有 x 轴日期的图表仅显示一些日期
【发布时间】:2020-07-08 16:24:25
【问题描述】:

我有 2 个数组:


 dates = [datetime.date(2019, 12, 9), datetime.date(2019, 12, 10),
       datetime.date(2019, 12, 12), datetime.date(2019, 12, 13),
       datetime.date(2019, 12, 14), datetime.date(2019, 12, 15),
       datetime.date(2019, 12, 16), datetime.date(2019, 12, 17),
       datetime.date(2019, 12, 18), datetime.date(2019, 12, 19)]

counts = [10, 2, 48067, 49791, 35347, 39418, 38817, 34269, 28066,
       22212]

我正在尝试创建一个图表来显示每个日期,但只显示几个

plt.figure(figsize=(100,10))

fig.tight_layout()
plt.xticks(rotation=90)

plt.plot(dates, counts)


plt.show()

我已经尝试关注this,但我仍然得到相同的结果 - 没有得到 x 轴上的所有日期

【问题讨论】:

    标签: python pandas matplotlib


    【解决方案1】:

    绘制图表后,您可以创建 DateLocatorDateFormatter 来更改 x 刻度的格式和频率。 cmets 的完整代码如下。

    import numpy as np
    import matplotlib.pyplot as plt
    import datetime
    import matplotlib.dates as mdates
    
    dates = [datetime.date(2019, 12, 9), datetime.date(2019, 12, 10),
             datetime.date(2019, 12, 12), datetime.date(2019, 12, 13),
             datetime.date(2019, 12, 14), datetime.date(2019, 12, 15),
             datetime.date(2019, 12, 16), datetime.date(2019, 12, 17),
             datetime.date(2019, 12, 18), datetime.date(2019, 12, 19)]
    
    counts = [10, 2, 48067, 49791, 35347, 39418, 38817, 34269, 28066, 22212]
    
    
    plt.figure(figsize=(100,10))
    fig.tight_layout()
    plt.xticks(rotation=90)
    plt.plot(dates, counts)
    
    ax=plt.gca()
    # Find the days in the data
    days = mdates.DayLocator()
    # Format the days in the data
    days_fmt = mdates.DateFormatter('%D')
    # Set xaxis to use the day locator
    ax.xaxis.set_major_locator(days)
    # Set xaxis to use the day formatter
    ax.xaxis.set_major_formatter(days_fmt)
    
    plt.show()
    

    这将生成以下图表,其中所有日期都以单独的刻度显示。

    有关更多日期格式的详细示例,请查看this sample

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-09
      • 2014-02-14
      • 1970-01-01
      • 2018-04-13
      • 2011-08-02
      • 2020-12-01
      • 2012-03-26
      相关资源
      最近更新 更多