TL; DR:在pandas中,如何绘制条形图以使其x轴刻度标签看起来像折线图?
我制作了一个时间间隔均匀的时间序列(每天一个项目),并且可以将它绘制成如此之好:
intensity[350:450].plot()
plt.show()
但是切换到条形图会造成这种混乱:
intensity[350:450].plot(kind = 'bar')
plt.show()
然后我直接使用matplotlib创建了一个条形图,但是它没有大熊猫的漂亮日期时间序列刻度标签格式化器:
def bar_chart(series):
fig, ax = plt.subplots(1)
ax.bar(series.index, series)
fig.autofmt_xdate()
plt.show()
bar_chart(intensity[350:450])
这里是强度系列的摘录:
intensity[390:400]
2017-03-07 3
2017-03-08 0
2017-03-09 3
2017-03-10 0
2017-03-11 0
2017-03-12 0
2017-03-13 2
2017-03-14 0
2017-03-15 3
2017-03-16 0
Freq: D, dtype: int64
我可以全力以赴,只需完全手工制作刻度标签,但我宁愿不必使用matplotlib,让我们做一下pandas的工作,并在第一个数字中做它所做的但是酒吧情节。那我该怎么做呢?
答案 0 :(得分:4)
大熊猫条形图是分类图。他们为每个类别创建一个刻度(+标签)。如果类别是日期并且那些日期是连续的,则可以旨在将某些日期留出,例如,仅绘制每五个类别,
ax = series.plot(kind="bar")
ax.set_xticklabels([t if not i%5 else "" for i,t in enumerate(ax.get_xticklabels())])
相比之下,matplotlib条形图是数字图。这里可以应用一个有用的自动收报机,每周,每月或任何需要的日期。
此外,matplotlib允许完全控制刻度位置及其标签。
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import dates
index = pd.date_range("2018-01-26", "2018-05-05")
series = pd.Series(np.random.rayleigh(size=100), index=index)
plt.bar(series.index, series.values)
plt.gca().xaxis.set_major_locator(dates.MonthLocator())
plt.gca().xaxis.set_major_formatter(dates.DateFormatter("%b\n%Y"))
plt.show()