相同图形上的Python绘图条形图和百分比折线图 [英] Python plot bar chart and percentage line chart on same graph
本文介绍了相同图形上的Python绘图条形图和百分比折线图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在同一张图表上绘制一条或多条折线作为条形图,以显示一些不同的指标.我听说我应该为此使用ax.twinx(),但是我得到一个错误,说x和y必须具有相同的第一维,或者由于我尝试过的两件事而读取0L时出现了不同的错误.这是我的代码;
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. 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)
注意; df4是一个分组的熊猫数据框.不确定这有多重要,以防万一.
Note; df4 is a grouped pandas dataframe. Not sure how relevant that is but just in case.
推荐答案
尝试一下:
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
这篇关于相同图形上的Python绘图条形图和百分比折线图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文