簡體   English   中英

使用 Pandas dataframe 索引作為 matplotlib plot 中 x 軸的值

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

我在 Pandas dateframe中有時間序列,其中包含許多我想要的列 plot。有沒有辦法將 x 軸設置為始終使用dateframe中的索引? 當我使用 Pandas 中的.plot()方法時,x 軸的格式正確,但是當我傳遞我的日期和列時,我想 plot 直接到 matplotlib 圖表不正確 plot。 提前致謝。

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

輸出

僅供參考: 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]')

您可以使用plt.xticks設置x軸

嘗試:

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

有關詳細信息,請參閱文檔: http//matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.xticks

似乎問題是我有.values 沒有它(即site2.index ),圖表會正確顯示

這是內置到plot() method

您可以使用yourDataFrame.plot(use_index=True)在 X 軸上使用 DataFrame 索引。

“use_index=True”在 X 軸上設置 DataFrame 索引。

在此處閱讀更多信息: https://pandas.pydata.org/pandas-docs/version/0.23/generated/pandas.DataFrame.plot.html

你想像我一樣使用 matplotlib 到 select 一個“明智”的規模,有一種方法可以解決這個問題。 使用 Pandas dataframe 索引作為 matplotlib plot 中 x 軸的值。代碼:

ax = plt.plot(site2['Cl'])
x_ticks = ax.get_xticks() # use matplotlib default xticks
x_ticks = list(filter(lambda x: x in range(len(site2)), x_ticks))
ax.set_xticklabels([' '] + site2.index.iloc[x_ticks].to_list())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM