I\'m trying to plot many data using subplots and I\'m NOT in trouble but I\'m wondering if there is a convenience method to do this.
below is the sample code.
subplots
returns an ndarray of axes objects, you can just flatten or ravel it:
fig, axes = plt.subplots(nrows = nrow, ncols=ncol, figsize=(8,6))
for ax in axes.flatten()[:20]:
# do stuff to ax
Rather than creating your subplots in advance using plt.subplots
, just create them as you go using plt.subplot(nrows, ncols, number)
. The small example below shows how to do it. It's created a 3x3 array of plots and only plotted the first 6.
import numpy as np
import matplotlib.pyplot as plt
nrows, ncols = 3, 3
x = np.linspace(0,10,100)
fig = plt.figure()
for i in range(1,7):
ax = fig.add_subplot(nrows, ncols, i)
ax.plot(x, x**i)
plt.show()
You could fill the final three in of course by doing plt.subplot(nrows, ncols, i)
but not calling any plotting in there (if that's what you wanted).
import numpy as np
import matplotlib.pyplot as plt
nrows, ncols = 3, 3
x = np.linspace(0,10,100)
fig = plt.figure()
for i in range(1,10):
ax = fig.add_subplot(nrows, ncols, i)
if i < 7:
ax.plot(x, x**i)
plt.show()
You may also like the look of GridSpec.