我正在尝试在同一个图形上绘制:线图和条形图,但线没有显示出来。代码如下:
df = pd.read_csv('cars.csv')
df['Price'] = pd.to_numeric(df['Price'])
m = df.groupby(['Brand', 'Year'])['Price'].mean()
s = df.groupby('Year').Price.mean()
ax = m.unstack('Brand').plot.bar()
s.plot(x=ax.get_xticks('Year'), ax=ax, kind='line', label='Mean price')
y_formatter = ScalarFormatter(useOffset=False)
plt.show()
我在这里做错了什么?
答案 0 :(得分:0)
这是因为条形图将 x
变量视为分类变量,因此条形会自动向下移动到 x=0,1,2,...
,并且它们的刻度通过 xticklabels
重新标记。您可以通过检查 ax.get_xlim()
和 ax.get_xticklabels()
来看到这一点。
一种解决方法是绘制 s
对 range(len(s))
以手动将其向下移动到 x=0,1,2,...
:
ax = m.unstack('Brand').plot.bar(legend=False)
ax.plot(range(len(s)), s, label='Mean price')
ax.legend()
或者在 reset_index()
上 s
两次并用 x='index'
绘图:
ax = m.unstack('Brand').plot.bar()
s.reset_index().reset_index().plot(x='index', y='Price', ax=ax, label='Mean price')