Remove excess stocks in matplotlib figure

How to determine if subplot ( AxesSubplot) is empty or not? I would like to deactivate empty axes of empty subplots and delete completely empty lines.

For example, in this figure, only two subheadings are filled in, and the remaining subheadings are empty.

import matplotlib.pyplot as plt

# create figure wit 3 rows and 7 cols; don't squeeze is it one list
fig, axes = plt.subplots(3, 7, squeeze=False)
x = [1,2]
y = [3,4]

# plot stuff only in two SubAxes; other axes are empty
axes[0][1].plot(x, y)
axes[1][2].plot(x, y)

# save figure
plt.savefig('image.png')

Note. Be sure to install squeezein False.

Mostly I want a rare figure. Some subnets in rows may be empty, but they must be deactivated (axes should not be visible). Completely empty lines must be deleted and must not be set to invisible.

+4
source share
2 answers

, , matplotlibs subplot2grid. , (3,7 ) . :

import matplotlib.pyplot as plt

x = [1,2]
y = [3,4]

fig = plt.subplots(squeeze=False)
ax1 = plt.subplot2grid((3, 7), (0, 1))
ax2 = plt.subplot2grid((3, 7), (1, 2))

ax1.plot(x,y)
ax2.plot(x,y)

plt.show()

:

enter image description here

EDIT:

Subplot2grid, , . fig, axes = plt.subplots(3, 7, squeeze=False), axes[0][1].plot(x, y), , . , , subplot2grid, , .

, ax1 = plt.subplot2grid((3, 7), (0, 1)) , "", 3 7. , 21 , , , , . , , subplot2grid - . (3,7) ax1 = ... , (0,1) , , .

, , 3x7. 21 , , , ax21 = plt.subplot2grid(...).

+4

fig.delaxes():

import matplotlib.pyplot as plt

# create figure wit 3 rows and 7 cols; don't squeeze is it one list
fig, axes = plt.subplots(3, 7, squeeze=False)
x = [1,2]
y = [3,4]

# plot stuff only in two SubAxes; other axes are empty
axes[0][1].plot(x, y)
axes[1][2].plot(x, y)

# delete empty axes
for i in [0, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 16, 17,
          18, 19, 20]:
    fig.delaxes(axes.flatten()[i])

# save figure
plt.savefig('image.png')
plt.show(block=False)
+5
source

Source: https://habr.com/ru/post/1648754/


All Articles