matplotlib.units.ConversionError: Failed to convert value to axis units 的解决

  • 背景故事
  • 问题再现
  • 解决 bug
    • 第一次尝试
    • 第二次尝试
      • 函数 plt.show() 的作用
      • 为什么 jupyter 中不使用 plt.show() 也不会报错
  • 结尾

背景故事

  • 最近两天在做日志分析,想整个 周访问量折线图月访问量柱状图
  • jupyter 中代码运行的没有问题,正确的显示了图像
  • 而当我将代码复制粘贴到 py 文件中就报了错

问题再现

  • 我的代码
'''
df.create_time
0       2020-12-22 11:17:29
1       2020-12-22 11:17:29
2       2020-12-22 11:17:30
3       2020-12-22 11:17:30
4       2020-12-22 11:17:31...
66370   2021-04-13 11:20:24
66371   2021-04-13 11:48:08
66372   2021-04-13 11:48:08
66373   2021-04-13 12:07:17
66374   2021-04-13 12:07:17
Name: create_time, Length: 66375, dtype: datetime64[ns]
'''
# 周访问量折线图
week_split = df.groupby(df.create_time.dt.week)['create_time'].count()
weekly = pd.date_range(df.iloc[0].create_time, periods=len(week_split), freq='w')
week_plot = plt.plot(weekly, week_split, marker='^', label='count')
plt.legend()# 月访问量柱状图
month_split = df.groupby(df.create_time.dt.month)['create_time']
months = ['%d月' % i for i in month_split.groups.keys()]
# 报错的那一句
month_bar = plt.bar(months, month_split.count().values, color='orange', width=0.3)plt.show()
  • 结果运行的时候报了个错
matplotlib.units.ConversionError: Failed to convert value(s) to axis units