python matplotlib日期被压缩在一起

mu0hgdu0  于 2023-11-22  发布在  Python
关注(0)|答案(2)|浏览(237)

下面是我的代码:

  1. # Graph for both infections and closures
  2. # # plotting the points
  3. plt.plot(graph_date, graph_daily_infections, label = "Infections per day")
  4. plt.plot(graph_date, graph_total_infections, label = "Infection overall")
  5. plt.plot(graph_date, graph_daily_closure, label = "Closures per day")
  6. plt.plot(graph_date, graph_total_closure, label = "Closure overall")
  7. # # naming the x axis
  8. plt.xlabel('Date')
  9. # naming the y axis
  10. plt.ylabel('Number of Infections/Closure')
  11. # giving a title to my graph
  12. plt.title('Daily infections and closure overtime \n Infection Rate: {0} | Closure Threshold: {1}'.format(infectionRate,closeThreshold))
  13. # show a legend on the plot
  14. plt.legend()
  15. # # changing the scale of the x ticks at the bottom
  16. # # plt.locator_params(nbins=4)
  17. # # set size of the graph
  18. plt.rcParams["figure.figsize"] = (20,15)
  19. # # function to show the plot
  20. plt.show()

字符串
这段代码的问题是,当显示日期时,它们在x轴上被挤压在一起。
有没有办法只显示月份,或者只显示月份和年份?图表应该显示数据的时间间隔是4个月,所以只显示月份/年份和月份是理想的。谢谢!

eblbsuwk

eblbsuwk1#

尝试使用autofmt_xdate()自动格式化x轴。
根据matplotlib.org,您必须在plt.show()之前添加以下内容:

  1. fig, ax = plt.subplots()
  2. ax.plot(date, r.close)
  3. # rotate and align the tick labels so they look better
  4. fig.autofmt_xdate()

字符串
对于月份和年份,您可以添加:

  1. ax.fmt_xdata = mdates.DateFormatter('%Y-%m-%d')

z6psavjg

z6psavjg2#

下面是另一个食谱:

  1. import matplotlib.dates as mdates
  2. ax.xaxis.set_major_locator(mdates.MonthLocator())
  3. ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m"))

字符串
More information about different format options in matplotlib.mdates module的一个。

相关问题