Python 在 matplotlib 图中使用 Pandas 数据帧索引作为 x 轴的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22356881/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:47:55  来源:igfitidea点击:

Using a Pandas dataframe index as values for x-axis in matplotlib plot

pythonmatplotlibplotpandas

提问by Jason

I have time series in a Pandas dateframewith a number of columns which I'd like to plot. Is there a way to set the x-axis to always use the index from a dateframe? When I use the .plot()method from Pandas the x-axis is formatted correctly however I when I pass my dates and the column(s) I'd like to plot directly to matplotlib the graph doesn't plot correctly. Thanks in advance.

我在 Pandas 中有时间序列,dateframe其中包含许多我想绘制的列。有没有办法将 x 轴设置为始终使用 a 中的索引dateframe?当我使用.plot()Pandas 中的方法时,x 轴的格式正确,但是当我传递日期和列时,我想直接绘制到 matplotlib 中,图表绘制不正确。提前致谢。

plt.plot(site2.index.values, site2['Cl'])
plt.show()

output

输出

FYI: site2.index.valuesproduces this (I've cut out the middle part for brevity):

仅供参考:site2.index.values产生这个(为简洁起见,我已经剪掉了中间部分):

array([
    '1987-07-25T12:30:00.000000000+0200',
    '1987-07-25T16:30:00.000000000+0200',
    '2010-08-13T02:00:00.000000000+0200',
    '2010-08-31T02:00:00.000000000+0200',
    '2010-09-15T02:00:00.000000000+0200'
], 
dtype='datetime64[ns]')

采纳答案by Jason

It seems the issue was that I had .values. Without it (i.e. site2.index) the graph displays correctly.

问题似乎是我有.values. 没有它(即site2.index)图形显示正确。

回答by ycy

You can use plt.xticksto set the x-axis

您可以使用plt.xticks来设置 x 轴

try:

尝试:

plt.xticks( site2['Cl'], site2.index.values ) # location, labels
plt.plot( site2['Cl'] )
plt.show()

see the documentation for more details: http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.xticks

有关更多详细信息,请参阅文档:http: //matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.xticks