简体   繁体   English

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

[英]Python plot bar chart and percentage line chart on same graph

I am trying to plot one or more lines on the same chart as a bar chart to show a few different metrics. 我试图在条形图上绘制一条或多条线,以显示一些不同的指标。 I heard I should use ax.twinx() for this, but I either get an error saying x and y must have the same first dimension, or a different error reading 0L based on the two things I tried. 我听说我应该使用ax.twinx(),但是我得到一个错误,说x和y必须具有相同的第一个维度,或者根据我尝试的两个东西读取0L的不同错误。 Here is my code; 这是我的代码;

    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)

Note; 注意; df4 is a grouped pandas dataframe. df4是一个分组的pandas数据帧。 Not sure how relevant that is but just in case. 不确定那是多么相关,只是为了以防万一。

Try this: 尝试这个:

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

NOTE: if you want a tested solution, please provide a sample data 注意:如果您需要经过测试的解决方案,请提供样本数据

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM