I'm having trouble formatting the seaborn graph, where I overlaid two graphs (line & bar). Say I have the following code so far:
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
df1["a"].plot(kind='bar', color='blue', ax=ax1)
df2["b"].plot(kind='line', marker='d', ax=ax2)
ax.set_xticklabels(('2015', '2016', '2017', '2018', '2019', '2020'))
ax1.yaxis.tick_right()
ax1.set_ylabel('Label A')
ax2.yaxis.tick_left()
ax2.set_ylabel('Label B')
ax1.set_xticklabels(('2015', '2016', '2017', '2018', '2019', '2020'))
plt.show()
Which produce something like this:
I would really appreciate if I can get advice on how to:
Terribly sorry if I'm making basic mistakes here, but it would be very helpful as no one seem to be active in queries in my online course.
*edit: Please note that my screenshot has VERY large numbers on one of the y-axis as I just took picture of my actual working notebook. However, please feel free to use the following sample dataset for the demonstration:
df1 = [39, 30, 40, 36, 28, 42]
df2 = [5, 8, 7, 3, 2, 6]
Let's try address your problems with the code:
from matplotlib import ticker
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
# don't try to force tick left/right. Swap the axes
df1["a"].plot(kind='bar', color='blue', ax=ax2)
df2["b"].plot(kind='line', marker='d', ax=ax1)
ax1.set_xticklabels(('2015', '2016', '2017', '2018', '2019', '2020'))
# disable these
# ax1.yaxis.tick_right()
# ax2.yaxis.tick_left()
# format to percentage
ax2.yaxis.set_major_formatter(ticker.StrMethodFormatter("{x}%"))
ax1.set_ylabel('Label B')
ax2.set_ylabel('Label A')
fig.tight_layout()
plt.show()
And you get something like this:
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.