我想创建一个显示自定义日期时间索引的分组条形图-仅显示月份和年份而不是完整日期。我希望将这些条进行分组而不是堆叠。
我认为熊猫可以使用以下方法轻松解决此问题:
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'))
但是比我的标签完全消失了。而这个问题意味着,大熊猫和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()
所以现在我的想法不多了,希望输入
原因之所以ax.xaxis.set_major_locator(mdates.MonthLocator())
失败,是因为在引擎盖下,大熊猫将条形图绘制在上range(len(df))
,然后相应地重命名刻度。
绘制后可以获取xticklabel并将其重新格式化:
ax = testdata.plot.bar()
ticks = [tick.get_text() for tick in ax.get_xticklabels()]
ticks = pd.to_datetime(ticks).strftime('%b %Y')
ax.set_xticklabels(ticks)
得到与ImpotanceOfBeingErnest相同的结果:
另一种可能更好的方法是移动每列的条形。当您有许多列并希望减少xticks的数量时,这种方法会更好。
fig, ax = plt.subplots()
# define the shift
shift = pd.to_timedelta('1D')
# modify the base of each columns, can do with a for loop
ax.bar(testdata.index + shift, testdata["A"])
ax.bar(testdata.index, testdata["B"])
ax.bar(testdata.index - shift, testdata["C"])
ax.xaxis.set_major_locator(mdates.MonthLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %Y'))
plt.show()
输出:
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句