首页 > 解决方案 > Pandas/Matplotlib:如何更改 x 轴的比例

问题描述

我查看了一些关于绘图的教程。如果到目前为止我理解正确,我尝试通过 pandas 中的 matplotlib 模块创建一个绘图。为此,我创建了一个带有计数和时间跨度索引的 df:

我的数据框(我想分析每季度的报价量,因此我为第一季度创建了另一个 df 等等):

count_second_quarter = second_quarter.groupby("request_date").count()
count_second_quarter

request_date     quote_id   count
        
2019-04-01        94        94
2019-04-02        123       123
2019-04-03        423       423
2019-04-04        123       123
2019-04-05        312       312
... ... ...

然后我创建了第一个情节:

plt.plot(count_first_quarter['count'])
plt.plot(count_second_quarter['count'])

在此处输入图像描述

第一个问题,我想我正在混合 matplotlib 和 pandas 。如何更改 x 轴的比例?理想情况下,我想有一个情节,每个季度都有一条单独的线..

谢谢!

标签: pythonpandasmatplotlib

解决方案


我认为你需要的是.reset_index()在绘图之前。这将使 x 轴从 0 开始到 89,您可以使用更新它plt.xticks()

plt.plot(count_first_quarter.reset_index()['count'])
plt.plot(count_second_quarter.reset_index()['count'])
# update xticks
plt.xticks(range(90), range(1,91)
# update xlabel
plt.xlabel('Days')
# show legend
plt.legend(['Q1', 'Q2'])

推荐阅读