简体   繁体   中英

Modifying axes and labels of overlaid matplotlib

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:

  • avoid the overlap of labels and ticks
  • make the label B axis into a percentage from 0 ~ 100 (and yes, most of my data hover around 30%, but I want to indicate how low that is.) Basically, I wanted to try axes.ylim(("0","100")) but it didn't work for me.
  • showing the entire width of each bar (the very first and last bars got cut by axes but I'm really not sure how to avoid it)

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.

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