gpt4 book ai didi

python - 使用 date_range 时如何使 x 轴更详细

转载 作者:行者123 更新时间:2023-11-28 17:15:21 24 4
gpt4 key购买 nike

我正在尝试绘制我收到的月度数据图表。绘制数据时,绘图仅在 x 轴上显示年份,而不显示月份。我怎样才能让它在 x 刻度标签上也显示月份?

import pandas as pd
import numpy as np
new_index = pd.date_range(start = "2012-07-01", end = "2017-07-01", freq = "MS")
columns = ['0']
df = pd.DataFrame(index=new_index, columns=columns)

for index, row in df.iterrows():
row[0] = np.random.randint(0,100)
%matplotlib inline
df.loc['2015-09-01'] = np.nan
df.plot(kind="line",title="Data per month", figsize = (40,10), grid=True, fontsize=20)

enter image description here

最佳答案

您可以使用 matplotlib.ticker 中的 FixedFormatter 为自定义刻度定义您自己的格式化程序,如下所示:

...
ticklabels = [item.strftime('%b %Y') for item in df.index[::6]] # set ticks format: month name and year for every 6 elements of index
plt.gca().xaxis.set_ticks(df.index[::6]) # set new ticks for current x axis
plt.gca().xaxis.set_major_formatter(ticker.FixedFormatter(ticklabels)) # apply new tick format

...

enter image description here

如果使用 %b\n%Y 格式,则日期分两行: enter image description here

关于python - 使用 date_range 时如何使 x 轴更详细,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44564057/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com