-1

I am trying to make a 3D graph using Pyplot, and I can't remove the big white border around the graph. How can I remove it?

enter image description here

haley
  • 845
  • 1
  • 7
  • 15

1 Answers1

0

You can do it like this:

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np

# Create a figure and 3D axes
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')

# Create some 3D data
u = np.linspace(0, 2 * np.pi, 100)
v = np.linspace(0, np.pi, 100)
x = 10 * np.outer(np.cos(u), np.sin(v))
y = 10 * np.outer(np.sin(u), np.sin(v))
z = 10 * np.outer(np.ones(np.size(u)), np.cos(v))

# Plot the 3D surface
ax.plot_surface(x, y, z, rstride=4, cstride=4, color='b')

# Turn off the axis labels and ticks
ax.axis('off')

# Save the figure with reduced whitespace
plt.savefig('3d_plot_no_whitespace.png', bbox_inches='tight', pad_inches=0)

# Show the plot
plt.show()

This code will generate a 3D plot without the large white border around the graph, and it will save the plot as an image file with minimal whitespace.

In this code:

We create a 3D figure and axes using matplotlib. We generate some 3D data to plot as a surface. We use ax.axis('off') to turn off the axis labels and ticks, reducing the visual clutter. We save the figure with reduced whitespace using bbox_inches='tight' and pad_inches=0. Finally, we display the plot using plt.show().

Another way is to use fig.subplots_adjust

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np

# Create a figure and 3D axes
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')

# Create some 3D data
u = np.linspace(0, 2 * np.pi, 100)
v = np.linspace(0, np.pi, 100)
x = 10 * np.outer(np.cos(u), np.sin(v))
y = 10 * np.outer(np.sin(u), np.sin(v))
z = 10 * np.outer(np.ones(np.size(u)), np.cos(v))

# Plot the 3D surface
ax.plot_surface(x, y, z, rstride=4, cstride=4, color='b')

# Turn off the axis labels and ticks
ax.axis('off')

# Save the figure with adjusted subplot margins
fig.subplots_adjust(left=0, right=1, bottom=0, top=1)

plt.savefig('3d_plot_no_whitespace_adjusted.png', facecolor='none')

# Show the plot
plt.show()

In this code, we make use of fig.subplots_adjust(left=0, right=1, bottom=0, top=1) to set the subplot margins to remove the white border. The facecolor='none' argument in plt.savefig is used to save the figure with a transparent background, so you can see the effect of removing the white border.

This code will generate a 3D plot without the large white border around the graph, using the fig.subplots_adjust method.

Some useful information in this article on matplotlib and removing white borders in Python. It provided valuable insights into addressing white border margins in my Python plots.

XCFzLoc
  • 19
  • 1