【问题标题】:Plot two pandas seriers to one figure将两个熊猫系列绘制为一个图形
【发布时间】:2021-05-22 13:15:00
【问题描述】:

我正在尝试绘制:线图条形图在同一个图上,但线没有出现。代码如下:

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()

我在这里做错了什么?

【问题讨论】:

    标签: python pandas matplotlib bar-chart line-plot


    【解决方案1】:

    这是因为条形图将x 变量视为分类变量,因此条形图会自动向下移动到x=0,1,2,...,并且它们的刻度会通过xticklabels 重新标记。您可以通过检查ax.get_xlim()ax.get_xticklabels() 看到这一点。

    一种解决方法是将srange(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()
    

    或者在s 上两次reset_index() 并使用x='index' 绘图:

    ax = m.unstack('Brand').plot.bar()
    s.reset_index().reset_index().plot(x='index', y='Price', ax=ax, label='Mean price')
    

    【讨论】:

      猜你喜欢
      • 2018-01-28
      • 2016-05-16
      • 1970-01-01
      • 2016-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-07
      • 1970-01-01
      相关资源
      最近更新 更多