Remove The Extra Plot In The Matplotlib Subplot
I want to plot 5 data frames in a 2 by 3 setting (i.e. 2 rows and 3 columns). This is my code: However there is an extra empty plot in the 6th position (second row and third column
Solution 1:
Try this:
fig.delaxes(axes[1][2])
A much more flexible way to create subplots is the fig.add_axes()
method. The parameters is a list of rect coordinates: fig.add_axes([x, y, xsize, ysize])
. The values are relative to the canvas size, so an xsize
of 0.5
means the subplot has half the width of the window.
Solution 2:
Solution 3:
If you know which plot to remove, you can give the index and remove like this:
axes.flat[-1].set_visible(False) # to remove last plot
Solution 4:
Turn off all axes, and turn them on one-by-one only when you're plotting on them. Then you don't need to know the index ahead of time, e.g.:
import matplotlib.pyplot as plt
columns = ["a", "b", "c", "d"]
fig, axes = plt.subplots(nrows=len(columns))
for ax in axes:
ax.set_axis_off()
for c, ax inzip(columns, axes):
if c == "d":
print("I didn't actually need 'd'")
continue
ax.set_axis_on()
ax.set_title(c)
plt.tight_layout()
plt.show()
Solution 5:
Previous solutions do not work with sharex=True
. If you have that, please consider the solution below, it also deals with 2 dimensional subplot layout.
import matplotlib.pyplot as plt
columns = ["a", "b", "c", "d"]
fig, axes = plt.subplots(4,1, sharex=True)
plotted = {}
for c, ax inzip(columns, axes.ravel()):
plotted[ax] = 0if c == "d":
print("I didn't actually need 'd'")
continue
ax.plot([1,2,3,4,5,6,5,4,6,7])
ax.set_title(c)
plotted[ax] = 1if axes.ndim == 2:
for a, axs inenumerate(reversed(axes)):
for b, ax inenumerate(reversed(axs)):
if plotted[ax] == 0:
# one can use get_lines(), get_images(), findobj() for the propose
ax.set_axis_off()
# now find the plot above
axes[-2-a][-1-b].xaxis.set_tick_params(which='both', labelbottom=True)
else:
break# usually only the last few plots are empty, but delete this line if not the caseelse:
for i, ax inenumerate(reversed(axes)):
if plotted[ax] == 0:
ax.set_axis_off()
axes[-2-i].xaxis.set_tick_params(which='both', labelbottom=True)
# should also work with horizontal subplots# all modifications to the tick params should happen after thiselse:
break
plt.show()
2 dimensional fig, axes = plot.subplots(2,2, sharex=True)
Post a Comment for "Remove The Extra Plot In The Matplotlib Subplot"