Home > Software engineering >  How to access and remove all unwanted objects in a matplotlib figure manually?
How to access and remove all unwanted objects in a matplotlib figure manually?

Time:05-23

I am trying to understand the underlying concepts of matplotlib, especially Output

I saw that there is something like..

a.set_axis_off()

.. but this doesn't seem to be the right solution. Somewhere there seems to be some kind of padding that remains. It doesn't look like it's from some X/Y axis as it's the same for all four edges in both subplots.

Any help appreciated.

CodePudding user response:

Solution

Two things are needed: First we need to initialize the Figure with frameon=False:

fig, axes = plt.subplots(
    // ...
    frameon=False)

The space between the subplots can be removed using the subplot layout:

plt.subplots_adjust(wspace=.0, hspace=.0)

CodePudding user response:

For the finest level of layout control, you can position your axes manually instead of relying on matplotlib to do it for you. There are a couple of ways of doing this.

One option is Axes.set_position

# Random data
df = pd.DataFrame(np.random.randint(0,100,size=(100, 2)), columns=list('AB'))

# Create a pair of Axes and preconfigure the figure with red facecolor.
# Then plot a scatter
fig, axes = plt.subplots(1, 2, figsize=(10, 5), facecolor='r')
df.plot(kind='scatter', x='A', y='B', ax=axes[0]).set_position([0, 0, 0.5, 1])
df.plot(kind='scatter', x='B', y='A', ax=axes[1]).set_position([0, 0.5, 0.5, 1])

You could also use the old-fashioned Figure.add_axes method:

# Random data
df = pd.DataFrame(np.random.randint(0,100,size=(100, 2)), columns=list('AB'))

# Create a pair of Axes and preconfigure the figure with red facecolor.
# Then plot a scatter
fig = plt.figure(figsize=(10, 5), facecolor='r')
df.plot(kind='scatter', x='A', y='B', ax=fig.add_axes([0, 0, 0.5, 1]))
df.plot(kind='scatter', x='B', y='A', ax=fig.add_axes([0, 0.5, 0.5, 1]))
  • Related