我試圖使用 matplotlib 繪制一個堆疊區域圖,頂部有垂直線。我的 MWE 是:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# my data
df = pd.DataFrame(data={'date': pd.date_range(start='2020-09-01', freq='D', periods=100),
'x1': np.random.randint(80,200,size=100),
'x2': np.random.randint(50,90,size=100),
'x3': np.random.randint(50,100,size=100),
})
df = df.set_index('date')
df0 = df.query("index == 20201026") # points of interest
fig = plt.figure()
ax = fig.add_subplot(111)
df.plot(ax=ax, kind='area')
ax.vlines(df0.index, ymin=0, ymax=1000, color='k', lw=1)
# ax.vlines(pd.concat([df0,df0], axis=0).index, ymin=0, ymax=1000, color='k', lw=1, ls='--')
ax.set_ylim((0,400))
ax.legend(loc='lower right')
plt.show()
使用 繪制面積圖df,任何感興趣的點都在 中df0。如果只有一點,df0當我使用繪圖時vlines會出現錯誤
TypeError: ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
但如果我使用pd.concat([df0,df0], axis=0),則沒有問題vlines。為什么會這樣?我在檔案中找不到任何vlines必須接受多個垂直線的內容。
uj5u.com熱心網友回復:
Matplotlib 不知道如何處理pd.Index. 用于tolist解決問題:
ax.vlines(df0.index.tolist(), ymin=0, ymax=1000, color='k', lw=1)
# HERE ---^
@BigBen 提出的解決方案:
# HERE ---v
df.plot(ax=ax, kind='area', x_compat=True)
ax.vlines(df0.index, ymin=0, ymax=1000, color='k', lw=1)

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/447927.html
標籤:Python 熊猫 数据框 matplotlib
上一篇:Winform選取框進度條凍結
