Python X轴上的年份值

Python X轴上的年份值,python,matplotlib,Python,Matplotlib,正在尝试为数据帧生成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

正在尝试为数据帧生成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轴显示记录的索引编号,而不是年份列的值。

我的代码是:

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()

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

如果您使用的是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()

但是,如果要同时显示年和月,一种方法是在打印“年”和“月”之前将它们连接起来,并创建一个新的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')
它创建一个新列
日期
,可以用作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()
输出:


怎么了?你必须告诉我们。这里的读者不介意。