0

The following code results in a figure saved with large white spaces around it, while there is enough space to stretch the axes.

import matplotlib.pyplot as plt
import numpy as np

X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)


fig, ax = plt.subplots(1, 1, figsize=(10, 5), subplot_kw=dict(projection="3d"))
plt.subplots_adjust(0, 0, 1, 1, 0, 0)


surf = ax.plot_surface(X, Y, Z, linewidth=0, antialiased=False)

ax.view_init(elev=20, azim=-45, roll=0)

ax.set_box_aspect([5, 1, 1])  # Aspect ratio
ax.set_aspect("auto")

plt.show()

How do I stretch the plot? As both the data and box aspect ratios are free to adjust, I'd expect to have a solution that fills the entire available space.

Not that I do not want to use the bbox_inches='tight' when saving the plot, as the figure is already prepared at the right size to be inserted in a paper.

enter image description here

1 Answer 1

0

According to the Matplotlib Tight layout guide

You may provide (my note: to tight_layout) an optional rect parameter, which specifies the bounding box that the subplots will be fit inside. The coordinates are in normalized figure coordinates and default to (0, 0, 1, 1) (the whole figure).

If you pass an area larger than 1×1 you can "zoom in" on a certain area of the figure.

In your example, adding this line

fig.tight_layout(rect=[0.0, -0.45, 1.0, 1.5])

right before saving/plotting, results in the figure below

Zoomed in version of the plot, with preserved aspect ratio

which has the same size (1000x500 pixels) of the one from your code. You probably want to tune the rect values to correct for the horizontal misalignment of the figure.

Hope this helps!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.