【问题标题】:Python: display end of month instead of first day of monthPython:显示月末而不是月的第一天
【发布时间】:2021-03-13 03:09:06
【问题描述】:

当我使用matplotlib 绘制数据框时,它会显示当月的第一天。相反,我真正想要的是显示月底。我怎样才能使用matplotlib 做到这一点?

Date                  Miles  
2020-01-31            410.364502
2020-02-29           1190.701827
2020-03-31           2400.855076
2020-04-30            526.747960
2020-05-31           2044.158990
2020-06-30          13983.470617
2020-07-31          18911.396787
2020-08-31           9219.378732
2020-09-30          16039.311330
2020-10-31          16847.898328
2020-11-30           7452.507720


fig, ax = plt.subplots(dpi=800)
ax.plot(general_trend.index, general_trend['Miles'], linewidth=0.8,color='red')
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
ax.legend(loc='upper right', ncol=2,fontsize=4.5)
ax.tick_params(axis='both', which='major', labelsize=6)
fig.autofmt_xdate()
plt.show()

【问题讨论】:

  • 日期的格式是什么?它们在列表中吗?

标签: python pandas matplotlib


【解决方案1】:

可能有许多其他方法可以做到这一点,但您可以使用定位器和格式化程序来指定月末,并以 bymonthday=-1 为月份的显示基础。

general_trend['Date'] = pd.to_datetime(general_trend['Date'])
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

fig, ax = plt.subplots(figsize=(4,3),dpi=200)
ax.plot(general_trend['Date'], general_trend['Miles'], linewidth=0.8, color='red', label='Miles')

months = mdates.MonthLocator(interval=1, bymonthday=-1)
months_fmt = mdates.DateFormatter('%Y-%m-%d')
ax.xaxis.set_major_locator(months)
ax.xaxis.set_major_formatter(months_fmt)

ax.legend(loc='upper right', ncol=2, fontsize=4.5)
ax.tick_params(axis='x', which='major', labelsize=6, labelrotation=45)

plt.show()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-11
    • 1970-01-01
    • 2013-07-23
    • 2020-10-02
    • 2020-03-30
    • 2018-11-23
    • 1970-01-01
    相关资源
    最近更新 更多