python - Error DateFormatter found a value of x=0, 这是 matplotlib 条形图中的非法日期

标签 python matplotlib dateformatter

我正在尝试在 matplotlib 中绘制双条形图,其中 x 轴是日期值。 我的数据框如下:

+------------+----------+----------+
|            | Column A | Column B |
+------------+----------+----------+
| 2020-03-28 |        4 |      0.0 |
+------------+----------+----------+
| 2020-03-29 |      250 |     58.0 |
+------------+----------+----------+
| 2020-03-30 |       72 |     10.0 |
+------------+----------+----------+
| 2020-03-31 |       10 |      0.0 |
+------------+----------+----------+
| 2020-04-01 |        7 |      0.0 |
+------------+----------+----------+
|        ... |      ... |      ... |
+------------+----------+----------+
| 2020-05-12 |        6 |      0.0 |
+------------+----------+----------+
| 2020-05-13 |        2 |      0.0 |
+------------+----------+----------+
| 2020-05-14 |        9 |      0.0 |
+------------+----------+----------+
| 2020-05-15 |        5 |      0.0 |
+------------+----------+----------+
| 2020-05-16 |       35 |      1.0 |
+------------+----------+----------+

I wish to plot it with a bar plot, with the following code:

g.plot.bar()
ax = plt.gca()
ax.set_yscale('log')
ax.xaxis_date() 
ax.xaxis.set_major_formatter(mdates.DateFormatter('%m-%d'))

最后一行是为 x 轴中的刻度设置格式化程序,因为如果没有,它将显示整个月中的所有日期。当我尝试这样做时,它引发了以下异常:

ValueError: DateFormatter found a value of x=0, which is an illegal date; this usually occurs because you have not informed the axis that it is plotting dates, e.g., with ax.xaxis_date()

我已经搜索了很多这个错误,但我无法弄清楚代码/数据出了什么问题......

最佳答案

据说 pandas 不能很好地处理自定义日期格式。
所以我们可以改用基础 matplotlib。
这个其他的答案帮助了我:https://stackoverflow.com/a/59739281/42346

import matplotlib.pyplot as plt, numpy as np, matplotlib.dates as mdates 

x = mdates.datestr2num(g.index.strftime('%m-%d')) 
w = 0.25
fig = plt.figure(figsize=(8, 4)) 
ax = fig.add_subplot(111) 
ax.bar(x - w, g['Column A'], width=2 * w, align='center') 
ax.bar(x + w, g['Column B'], width=2 * w, align='center') 
ax.xaxis_date() 
ax.xaxis.set_major_locator(mdates.AutoDateLocator()) 
ax.xaxis.set_major_formatter(mdates.DateFormatter("%m-%d"))
plt.show()

结果:

enter image description here

关于python - Error DateFormatter found a value of x=0, 这是 matplotlib 条形图中的非法日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61966334/

相关文章:

python - 如何为乘法表创建 while 循环?

python - 如何让python重新将连续匹配模式选项视为模式的单次出现?

ios - 将日期格式iso-8601更改为自定义格式

python - list.index 的 Numpy 等价物

python - 为什么 setuptools 不创建我的入口点?

python - 找到轮廓曲线中距离最远的点

python - 将 imshow 与共享 x 轴与 matplotlib 一起使用

python - matplotlib 中是否有制作散点图矩阵的功能?

swift - DateFormatter 在特定设备上返回 nil

java - 在 Spring Boot 中接受阿拉伯日期作为查询参数