Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rotate secondary y axis label so it doesn't overlap with y-ticks, matplotlib

I am trying to rotate my secondary y-label to 270 degrees, but when I do this passing the rotate=270 argument it overlaps my y-tick text. Any ideas how to fix this?

fig, ax = plt.subplots()

ax.plot(df.index,df.tripTime,label='Fishing Effort', marker='D')
ax2=ax.twinx()
ax2.plot(tr.index,tr.cost, 'g',label='Fuel Expenditure', marker='d')

lines = ax.get_lines() + ax2.get_lines()
ax.legend(lines,[line.get_label() for line in lines], loc='lower left')
ax.set_ylim((0, 18))

ax2.set_ylabel('Cost ($)',color='g', rotation=270)

for tl in ax2.get_yticklabels():
    tl.set_color('g')

ax.set_ylabel('Fishing Effort (hrs)')
ax.set_xlabel('Time (days)')
plt.show()

enter image description here

like image 379
hselbie Avatar asked Jan 26 '16 17:01

hselbie


People also ask

How do you prevent labels from overlapping in MatPlotLib?

To avoid overlapping of labels and autopct in a matplotlib pie chart, we can follow label as a legend, using legend() method.

How do I rotate y labels in MatPlotLib?

Rotate X-Axis Tick Labels in Matplotlib There are two ways to go about it - change it on the Figure-level using plt. xticks() or change it on an Axes-level by using tick. set_rotation() individually, or even by using ax. set_xticklabels() and ax.

How do you rotate Xticks for all subplots?

To rotate tick labels in a subplot, we can use set_xticklabels() or set_yticklabels() with rotation argument in the method. Create a list of numbers (x) that can be used to tick the axes. Get the axis using subplot() that helps to add a subplot to the current figure.

How do I make Y-axis labels horizontal in MatPlotLib?

MatPlotLib with Python Just by using plt. ylabel(rotation='horizontal'), we can align a label according to our requirement.


1 Answers

UPDATE: This answer isn't very good, please look at the comments!

This looks like a bug and you should probably report it to matplotlib's issue tracker.

While it is getting fixed, a quick solution is to set the label padding to a higher value:

ax2.set_ylabel('Cost ($)', color='g', rotation=270, labelpad=15)

Result

Moreover, negative labelpad values can be used to decrease the white-space as well.

like image 107
smheidrich Avatar answered Sep 22 '22 03:09

smheidrich