Reputation: 1090
I am trying to find a method to remove the vertical white space from a figure generated and saved using matplotlib
. So, basically the white space above and below the axes.
The requiremens in my use case are the following:
The following command comes very close and removes the vertical white space, but it also removes the horizontal white space:
myFigure.savefig(myImagePath, bbox_inches='tight')
The optimal solution would be to apply the algorithm of bbox_inches='tight'
only to the y-axis of the plot...
Upvotes: 2
Views: 1177
Reputation: 339052
As said in the comments you would usually set the figure size and the subplotparams such that there is no space in the direction of choice. If the yaxis does have a given size which needs to be preserved you can first calculate its length, then adjust the figure size and subplot parameters such that the axis length is kept the same.
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(5,6), dpi=50)
ax.plot([1,2])
ax.set_ylabel("ylabel")
ax.set_xlabel("xlabel")
### 1. Original image
ax.set_title("original")
plt.savefig("fsi01.png", facecolor="#edf9f9")
### 2. tight bbox
ax.set_title('bbox_inches="tight"')
plt.savefig("fsi02.png", facecolor="#edf9f9", bbox_inches="tight")
### 3. Only vertical adjustent
axes_height = fig.get_size_inches()[1]*(fig.subplotpars.top-fig.subplotpars.bottom)
top = 0.94; bottom=0.09
fig.subplots_adjust(top=top,bottom=bottom)
fig.set_size_inches((fig.get_size_inches()[0],axes_height/(top-bottom)))
ax.set_title('only vertical adjust')
plt.savefig("fsi03.png", facecolor="#edf9f9")
plt.show()
Of course the values top = 0.94; bottom=0.09
would need to be determined in each case individually.
Upvotes: 1
Reputation: 1980
you wan to use autoscale (assuming you're using pyplot as plt)
plt.autoscale(enable=True, axis='y', tight=True)
Upvotes: 0