When I save off a matplotlib figure, I have unequal whitespace around the box containing my figure, since the left side has the axis markings (ditto for the bottom side).
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 1, 32)
plt.plot(x, x**2)
plt.show()
Is there a way I can center the box in the image?
CodePudding user response:
You could extract the current left, right, bottom and top margins, and then set them to the maximum in the two directions.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 1, 32)
plt.plot(x, x ** 2)
fig = plt.gcf()
left = max(fig.subplotpars.left, 1 - fig.subplotpars.right)
bottom = max(fig.subplotpars.bottom, 1 - fig.subplotpars.top)
fig.subplots_adjust(left=left, right=1 - left, bottom=bottom, top=1 - bottom)
plt.show()