如何获得X轴上的正确值或索引?

时间:2019-04-04 12:26:58

标签: python python-3.x matplotlib charts

我有类似这样的数据。

    Year  Quarter  Quantity  Price
0   2000        1        23    142
1   2000        2        23    144
2   2000        3        23    147
3   2000        4        23    151
4   2001        1        22    160
5   2001        2        22    183
6   2001        3        22    186
7   2001        4        22    186
8   2002        1        21    212
9   2002        2        19    232
10  2002        3        19    223

我试图在x轴上显示年份,但我一直在努力寻找方法。这是我的示例代码。

df1 = df.groupby(['Year']).agg({'Quantity':'sum','Price':'sum'}).reset_index()
price = df1.Price
mean_x = pd.Series(df1.Price).rolling(window=4).mean()


# plot price of policies sold per year along with moving average of same
plt.title('Price of Policies Sold Over Time')
plt.xlabel('Year')
plt.ylabel('Policies')
plt.legend(loc = 'upper left')
plt.plot(df1.Year.values, price, label='Policy Prices')
plt.plot(df1.Year.values, mean_x, label='Policy Prices')
plt.plot(mean_x, label='Moving Average of Policy Prices')
plt.show()

这是结果。

enter image description here

因此,我想在x轴上显示年份。如何显示年份值?

1 个答案:

答案 0 :(得分:0)

我终于开始工作了。我的解决方案如下所示。

df1 = df.groupby(['Year']).agg({'Quantity':'sum','Price':'sum'}).reset_index()
price = df1.Price

# moving average below
mean_x = pd.Series(df1.Price).rolling(window=4).mean()

# plot price of policies sold per year along with moving average of same
plt.title('Price of Policies Sold Over Time')
plt.xlabel('Year')
plt.ylabel('Policies')
plt.plot(df1.Year, df1.Price, label='Policy Prices')
plt.plot(df1.Year, mean_x, label='Moving Average Prices')
plt.legend()
plt.show()

enter image description here