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)
Note; df4 is a grouped pandas dataframe. 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.