ramgorur
ramgorur

Reputation: 2162

matplotlib how to crop a plot so that all white border/padding is removed?

Let's say I am doing a 3D scatter plot with matplotlib. I am using the code given here: https://matplotlib.org/2.1.1/gallery/mplot3d/scatter3d.html

For my purposes I need to remove the axes, ticklevels etc. So I am doing this:

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

ax.set_xticklabels([])
ax.set_yticklabels([])
ax.set_zticklabels([])
ax.set_axis_off()

I am also removed all the axis labels. To remove the white padding, I am saving the figure like this:

plt.savefig("test.png", bbox_inches = 'tight', pad_inches = 0)
plt.show()

But still there are white paddings, the generated figure looks like this: enter image description here

But what I want is a figure that bounds only the portion of the figure where all the data points are, like this:

enter image description here

Upvotes: 5

Views: 9950

Answers (1)

busybear
busybear

Reputation: 10590

Use subplots_adjust. This will remove any space around (and between, if there were multiple) axes, so there is no "figure deadspace".

fig, ax = plt.subplots()
ax.scatter(np.random.random(100), np.random.random(100))
ax.set_axis_off()
fig.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=0, hspace=0)
fig.savefig('test.png', edgecolor='r', lw=2)  # red line to highlight extent of figure

enter image description here

versus without subplots_adjust

enter image description here

Upvotes: 6

Related Questions