【发布时间】:2020-02-08 08:43:36
【问题描述】:
我想创建一个显示自定义日期时间索引的分组条形图 - 仅显示月份和年份,而不是完整日期。我希望条形图被分组而不是堆叠。
我认为 pandas 可以轻松处理这个问题,使用:
import pandas as pd
import matplotlib.pylab as plt
import matplotlib.dates as mdates
testdata = pd.DataFrame({"A": [1, 2, 3]
,"B": [2, 3, 1]
, "C": [2, 3, 1]}
,index=pd.to_datetime(pd.DatetimeIndex(
data=["2019-03-02", "2019-04-01","2019-05-01"])))
ax = testdata.plot.bar()
这会创建我想要的情节,我只想将日期更改为更简单的内容,例如 2019 年 3 月、2019 年 4 月、2019 年 5 月。
我认为使用自定义日期格式化程序会起作用,因此我尝试了
ax.xaxis.set_major_locator(mdates.MonthLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %Y'))
但是我的标签已经完全消失了。而this question 暗示 pandas 和 DateFormatter 的关系有点困难。因此我尝试使用 Matplotlib 基础知识:
fig, ax = plt.subplots()
width = 0.8
ax.bar(testdata.index, testdata["A"])
ax.bar(testdata.index, testdata["B"])
ax.bar(testdata.index, testdata["C"])
ax.xaxis.set_major_locator(mdates.MonthLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %Y'))
plt.show()
现在日期表示符合预期(尽管可以减少空格),但数据重叠,这无济于事。
由于我使用的 DateTime-Index,定义宽度并从 x 值中减去它(如通常建议的那样)将无济于事。我收到一个错误,即不支持减去 DatetimeIndes 和 float。
fig, ax = plt.subplots()
width = 0.8
ax.bar(testdata.index-width, testdata["A"])
ax.bar(testdata.index, testdata["B"])
ax.bar(testdata.index+width, testdata["C"])
ax.xaxis.set_major_locator(mdates.MonthLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %Y'))
plt.show()
所以现在我的想法已经不多了,希望得到输入
【问题讨论】:
标签: python pandas matplotlib