Second y-axis label getting cut off

PythonGraphMatplotlib

Python Problem Overview


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

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionzjeView Question on Stackoverflow
Solution 1 - PythonzjeView Answer on Stackoverflow
Solution 2 - PythonElliotView Answer on Stackoverflow