2
votes

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

1
use ax.set_xlim and ax.set_ylim to limit your plot window to your liking - Arjun
Since you want to also crop part of the invisible axes, there is no automated solution to this. Instead of bbox_inches = 'tight' you will need to provide a custom bounding box, with the extent you desire. - ImportanceOfBeingErnest
@ImportanceOfBeingErnest How do I do that? - ramgorur
@Arjun Is there anyway I can detect the bound of xlim, ylim or zlim from the figure itself? Not by using the coordinate values? - ramgorur
Maybe bbox_inches = matplotlib.transforms.Bbox.from_extents(1,1,5,3.8)? change the numbers to your liking. - ImportanceOfBeingErnest

1 Answers

4
votes

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