X轴上的年份值

2024-10-04 11:28:00 发布

您现在位置:Python中文网/ 问答频道 /正文

尝试为数据帧生成gtraph:

   year  month    k_mean  k_min  k_max  k_count
0  1994      1  3.548387    2.0    5.0      9.0
1  1994      2  4.500000    2.0    7.0     15.0
2  1994      3  4.387097    2.0    7.0     16.0
3  1994      4  4.433333    1.0    9.0     16.0
4  1994      5  4.806452    2.0    7.0     20.0

x轴显示记录的索引编号,而不是年份列的值。 enter image description here

我的代码是:

import matplotlib.pyplot as plt
x0=result.year.astype(np.int32).unique()
y1=result.k_max.astype(np.int32)
x0, y1.plot(label='1')
y2=result.k_count.astype(np.int32)
x0, y2.plot(label='2')
plt.legend(loc='best')
plt.show()

怎么了?理想的情况是,我想要一年和一个月。谢谢。你知道吗


Tags: 数据plotcountnppltresultyearlabel
2条回答

如果您使用的是Pandas dataframe(名称为df),则可以使用以下简单命令生成图形:

ax=plt.gca()
df.plot(kind='line',x='month',y='k_max',ax=ax)
df.plot(kind='line',x='month',y='k_count',color='blue',ax=ax)
plt.show()

enter image description here

但是,如果要同时显示年和月,一种方法可以是在绘制它们之前将“年”和“月”串联起来,并创建一个新的x变量,如下所示: 1994-1 1994-2 ... 你知道吗

要用年和月来绘图,最好用这种方法调整一下df:

result['date'] = pd.to_datetime(result['year'].astype(str)+'-'+result['month'].astype(str), format='%Y-%m').dt.strftime('%Y-%m')

它创建一个新列date,可以用作x轴:

   year  month    k_mean  k_min  k_max  k_count     date
0  1994      1  3.548387    2.0    5.0      9.0  1994-01
1  1994      2  4.500000    2.0    7.0     15.0  1994-02
2  1994      3  4.387097    2.0    7.0     16.0  1994-03
3  1994      4  4.433333    1.0    9.0     16.0  1994-04
4  1994      5  4.806452    2.0    7.0     20.0  1994-05

在此之后,您可以使用它来绘制图形中的两列:

import matplotlib.pyplot as plt
result.plot(x='date', y=['k_max', 'k_count'])
plt.show()

输出:

enter image description here

相关问题 更多 >