Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Second y-axis label getting cut off

I'm trying to plot two sets of data in a bar graph with matplotlib, so I'm using two axes with the twinx() method. However, the second y-axis label gets cut off. I've tried a few different methods with no success (tight_layout(), setting the major_pads in rcParams, etc...). I feel like the solution is simple, but I haven't come across it yet.

Here's a MWE:

#!/usr/bin/env python import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt  matplotlib.rcParams.update({'font.size': 21}) ax = plt.gca() plt.ylabel('Data1') #Left side ax2 = ax.twinx() for i in range(10):   if(i%2==0):     ax.bar(i,np.random.randint(10))   else:     ax2.bar(i,np.random.randint(1000),color='k')   plt.ylabel('Data2') #Right 

side plt.savefig("test.png")

Sample graph with Data2 cut off

like image 693
zje Avatar asked Jan 22 '14 16:01

zje


People also ask

How do you label the second Y axis?

To create a second y-axis, we use the twinx() function. To add a label at secondary y-axis, we use the set_ylabel() function. To set the same color of the axes label as plotting line pass color parameter to set_ylabel() method.

What label goes on the y axis?

The independent variable belongs on the x-axis (horizontal line) of the graph and the dependent variable belongs on the y-axis (vertical line).

How do you change the Y axis labels in python?

To set labels on the x-axis and y-axis, use the plt. xlabel() and plt. ylabel() methods.

How do I remove the Y axis labels?

When we create a plot in R, the Y-axis labels are automatically generated and if we want to remove those labels, the plot function can help us. For this purpose, we need to set ylab argument of plot function to blank as ylab="" and yaxt="n" to remove the axis title.


2 Answers

I just figured it out: the trick is to use bbox_inches='tight' in savefig.

E.G. plt.savefig("test.png",bbox_inches='tight')

fixed now

like image 190
zje Avatar answered Sep 22 '22 18:09

zje


I encountered the same issue which plt.tight_layout() did not automatically solve.
Instead, I used the labelpad argument in ylabel/set_ylabel as such:

ax.set_ylabel('label here', rotation=270, color='k', labelpad=15)

I guess this was not implemented when you asked this question, but as it's the top result on google, hopefully it can help users of the current matplotlib version.

like image 30
Elliot Avatar answered Sep 21 '22 18:09

Elliot