python matplotlib日期被压缩在一起

mu0hgdu0  于 6个月前  发布在  Python
关注(0)|答案(2)|浏览(58)

下面是我的代码:

# Graph for both infections and closures

# # plotting the points  
plt.plot(graph_date, graph_daily_infections, label = "Infections per day")
plt.plot(graph_date, graph_total_infections, label = "Infection overall")
plt.plot(graph_date, graph_daily_closure, label = "Closures per day")  
plt.plot(graph_date, graph_total_closure, label = "Closure overall") 
# # naming the x axis 
plt.xlabel('Date') 
# naming the y axis 
plt.ylabel('Number of Infections/Closure') 
# giving a title to my graph 
plt.title('Daily infections and closure overtime \n Infection Rate: {0} | Closure Threshold: {1}'.format(infectionRate,closeThreshold)) 
# show a legend on the plot
plt.legend()
# # changing the scale of the x ticks at the bottom

# # plt.locator_params(nbins=4)

# # set size of the graph
plt.rcParams["figure.figsize"] = (20,15)
# # function to show the plot

plt.show()

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

eblbsuwk

eblbsuwk1#

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

fig, ax = plt.subplots()
ax.plot(date, r.close)

# rotate and align the tick labels so they look better
fig.autofmt_xdate()

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

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

z6psavjg

z6psavjg2#

下面是另一个食谱:

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

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

相关问题