Python绘图条形图和百分比折线图在同一图形上

JD2015

我正在尝试在与条形图相同的图表上绘制一条或多条线,以显示一些不同的指标。我听说我应该为此使用ax.twinx(),但是我得到一个错误,说x和y必须具有相同的第一维,或者由于我尝试过的两件事而读取0L时出现了不同的错误。这是我的代码;

    x = df4['Date']
    y = df4['Rate']
    ax = df4[['Date','Qty']].set_index('Date') \
                            .plot(kind='bar',
                                  stacked=False,
                                  color = 'dodgerblue',
                                  figsize=(13,4),
                                  legend=True)
    ax.set_xlabel(r"$\rm \bf{Date}$",
                  fontsize=18, 
                  rotation = 0)
    ax.set_ylabel(r'$\cal \bf{Qty}$ ',fontsize=18, rotation = 90)

    ax2 = ax.twinx()
    ax2.plot(x, y, color = 'green', linestyle = '--', linewidth= 2.0)

注意; df4是一个分组的熊猫数据框。不知道这有多重要,但以防万一。

最大容量

试试这个:

fig, ax = plt.subplots()
ax2 = ax.twinx()


df4[['Date','Qty']].set_index('Date') \
                   .plot(kind='bar',
                         ax=ax,
                         color = 'dodgerblue',
                         figsize=(13,4),
                         legend=False)

patches, labels = ax.get_legend_handles_labels()
ax.legend(patches, labels, loc='upper left')

ax.set_xlabel(r"$\rm \bf{Date}$", fontsize=18, rotation=0)
ax.set_ylabel(r'$\cal \bf{Qty}$ ',fontsize=18, rotation=90)

ax2.plot(range(len(df4)), df4['Rate'], 'green', label='Rate',
         linestyle = '--', linewidth=2.0)

patches, labels = ax2.get_legend_handles_labels()
ax2.legend(patches, labels, loc='upper right')

注意:如果您需要经过测试的解决方案,请提供样本数据

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章