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_pad
s 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")
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.
The independent variable belongs on the x-axis (horizontal line) of the graph and the dependent variable belongs on the y-axis (vertical line).
To set labels on the x-axis and y-axis, use the plt. xlabel() and plt. ylabel() methods.
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.
I just figured it out: the trick is to use bbox_inches='tight'
in savefig
.
E.G. plt.savefig("test.png",bbox_inches='tight')
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With