Reputation: 3912
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")
Upvotes: 58
Views: 68840
Reputation: 103
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.
Upvotes: 7
Reputation: 3912
I just figured it out: the trick is to use bbox_inches='tight'
in savefig
.
E.G. plt.savefig("test.png",bbox_inches='tight')
Upvotes: 146