python - 如何用一定数量的子图填充图形?

标签 python matplotlib

各位程序员大家好!

我正在尝试编写代码来创建matplotlib.pyplot.figure并用子图填充它。唯一的输入应该是子图的数量。在这种情况下,每个白框代表一个子图

以下示例适用于可被 100 整除的 subplot 数字:

import matplotlib.pyplot as plt

subplots = 200
cols = int(round(subplots/10))
rows = int(round(subplots/20))

print(f'subplots: {cols*rows}')

fig, axes = plt.subplots(nrows=rows, ncols=cols)
_axes = []
for ax_array in axes:
    for ax in ax_array:
        _axes.append(ax)

for ax in _axes:
    ax.set_xticklabels([])
    ax.set_yticklabels([])
    ax.tick_params(axis='both', which='both', length=0)
    ax.plot()

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

输出:

subplots: 200

enter image description here

该图正确描绘了 200 个子图。

但是当我进行更改subplots = 150时,子图数量的计算和描述是错误的:

subplots: 120

enter image description here

如何计算描绘子图所需的正确的nrowsncols数量?如果需要的话,我希望figure能够描绘149个subplots

有更好的方法吗?

提前谢谢您。

最佳答案

尝试替换这个:

rows = int(round(subplots/20))

这样:

rows = int(round(subplots/cols))

这将修复计算出的子图数量。


plt.subplots()定义一个由子图组成的矩形网格,它们的总数不应该是素数,因为它必须能被列数和行数整除。如果您输入素数 subplots ,您的代码将找到最近的非质数。例如,如果您输入:

subplots = 149

您的代码将为您提供 150子图,因为它不存在 cols * rows 的组合这给出了 149作为一个产品。

为了管理它,请使用以下代码:

import matplotlib.pyplot as plt

subplots = 149
cols = int(round(subplots/10))
rows = int(round(subplots/cols))

print(f'subplots: {cols*rows}')

if subplots > cols * rows:
    fig, axes = plt.subplots(nrows = rows + 1, ncols = cols)
else:
    fig, axes = plt.subplots(nrows = rows, ncols = cols)

_axes = []
for ax_array in axes:
    for ax in ax_array:
        _axes.append(ax)

for ax in _axes:
    ax.set_xticklabels([])
    ax.set_yticklabels([])
    ax.tick_params(axis='both', which='both', length=0)
    ax.plot()

if subplots > cols * rows:
    for idx in range(1, cols):
        fig.delaxes(axes[rows, idx])
elif subplots < cols * rows:
    fig.delaxes(axes[rows - 1, cols - 1])

plt.tight_layout()
plt.subplots_adjust(wspace=0, hspace=0)
plt.show()
  • subplots > rows * cols 的情况下(例如 subplots = 31 )它将在底部添加一个子图:

enter image description here

  • subplots < rows * cols 的情况下(例如 subplots = 23 )它将删除最后一个子图:

enter image description here

这样您就可以管理所有案例。

关于python - 如何用一定数量的子图填充图形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62244810/

相关文章:

python - Pandas 在 x 轴上绘制 : Separate color for weekends, pretty-print 时间

python - Pandas groupby将不连续的视为不同的变量?

python - 如何在 matplotlib (python) 中标记一条线?

python - Matplotlib 及其与 tkinter 的连接

python - Google Colaboratory 中的 openAI Gym NameError

python - 使用 matplotlib 绘制两行标签贴

python - 指向曲线上一点的箭头

python - 如何在 Ubuntu 中将 kivy 和 python 打包为可执行文件?

Python 3 打印()函数

Python SQLite3 SELECT 中的多个变量