By default, matplotlib subplots are filled by row, not by column. To clarify, the commands
plt.subplot(nrows=3, ncols=2, idx=2)
plt.subplot(nrows=3, ncols=2, idx=3)
first plot into the upper right plot of the 3x2 plot grid (idx=2), and then into the middle left plot (idx=3).
Sometimes it may be desirable for whatever reason to fill the subplots by row, not by column (for example, because directly consecutive plots belong together and are easier interpretable when positioned below each other, rather than next to each other). How can this be achieved?
You can create the 3x2 array of axes using:
fig, axes = plt.subplots(nrows=3, ncols=2)
If you transpose this array, then flatten you can plot column wise, rather than row wise:
fig, axes = plt.subplots(nrows=3, ncols=2)
for ax in axes.T.flatten():
ax.plot([1,2,3])
There's probably a million (easy) ways to do this, but as it took me more than a minute to think about this, I thought I'd share my solution:
def row_based_idx(num_rows, num_cols, idx):
return np.arange(1, num_rows*num_cols + 1).reshape((num_rows, num_cols)).transpose().flatten()[idx-1]
With this, one can simply do
row_based_plot_idx = row_based_idx(num_rows, num_cols, col_based_plot_idx)
plt.subplot(num_rows, num_cols, row_based_plot_idx)
Just hoping this saves somebody a minute. Surely, there are better solutions available.
If you are forcing to use index
try this translator:
to_row_major_order = (lambda idx, n_row, n_col: ((idx - 1) % n_row) * n_col + int((idx - 1) / n_row) + 1)
# usage:
nrows = 3
ncols = 2
col_major_order_idx = 2
row_major_order_idx = to_row_major_order(col_major_order_idx, nrows, ncols)
plt.subplot(nrows=nrows, ncols=ncols, idx=row_major_order_idx)
Some ref: https://en.wikipedia.org/wiki/Row-_and_column-major_order
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.