繁体   English   中英

如何在 matplotlib 中为 Pandas 的 DatetimeIndex 自定义 xaxis 刻度?

[英]How to customize xaxis ticks for DatetimeIndex of Pandas in matplotlib?

我有这样的 pandas dataframe data

            num
Date        
2020-03-01  311
2020-03-08  432
2020-03-15  420
2020-03-22  304
2020-03-29  1030
2020-04-05  1497
2020-04-12  2259
2020-04-19  1938

其中DateDatetimeIndex 我尝试如下 plot 它;

from matplotlib import pyplot as plt
x = data.index
fig = plt.figure()
ax1 = fig.add_subplot(111)
tested_plot = ax1.bar(x, data["num"])
dates_fmt = mdates.DateFormatter('%m/%d')
ax1.xaxis.set_major_formatter(dates_fmt)
plt.show()

我希望 xaxis 中的刻度显示在条存在的位置(如 3/1、3/8、...、4/12、4/19)。 但是当我上面的 plot 时,四月开始时会重置刻度,并且条形和刻度不对应;

错误的图表

我知道我可以使用strftimeDatetimeIndex转换为字符串Index ,这将解决问题,但我想保留DatetimeIndex以进行进一步定制。 我也用过

import matplotlib.dates as mdates
ax1.xaxis.set_major_locator(mdates.DayLocator(interval=7))

强制刻度相隔一周,但是我无法设置刻度的开始日期,现在刻度上没有条形。 有人知道如何解决这个问题吗?

你可以试试pandas.DataFrame.plotmatplotlib.axes.Axes.set_xticklabels . set_xticklabels方法中,您可以根据需要格式化日期(此处使用pandas.Series.dt.strftime ):

df.plot(kind="bar", ax=ax1)
ax1.set_xticklabels([date.strftime("%Y-%m-%d") for date in df.index], 
                     rotation=45)

完整代码

# Be sure dates are datetime objects
# df["Date"] = pd.to_datetime(df["Date"])
# df.set_index("Date", inplace=True)

print(df)
#              num
# Date
# 2020-03-01   311
# 2020-03-08   432
# 2020-03-15   420
# 2020-03-22   304
# 2020-03-29  1030
# 2020-04-05  1497
# 2020-04-12  2259
# 2020-04-19  1938

fig = plt.figure()
ax1 = fig.add_subplot(111)
df.plot(kind="bar", ax=ax1)
ax1.set_xticklabels([date.strftime("%Y-%m-%d") for date in df.index], 
                    rotation=45)
plt.show()

output

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM