在 matplotlib 堆积面积图上绘制垂直线
Plotting vertical line on matplotlib stacked area graph
我尝试使用 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
必须接受一条以上的垂直线。
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)
我尝试使用 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
必须接受一条以上的垂直线。
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)