打印灵活网格时,删除/隐藏matplotlib中的空子地块

2024-04-27 17:16:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我用nilearn绘制了一系列的切割,沿着一个轴穿过大脑的3D图像文件。我的目标是制作一个灵活的函数,在这个函数中,我可以随意更改行数、列数和切割的坐标范围。这样做的原因是,我可以生成一个.png文件并将其用于可视化,例如直接在一篇论文中

所以基本上我使用嵌套循环,生成matplotlib子图的网格,并用大脑图像填充它们。它们来自nilearn函数的一行代码,所以这不是问题所在

我的问题是:有没有办法检测和隐藏/删除空子批次? 问题是,现在空的子窗口会显示一条错误消息,这似乎会弄乱它返回的.png文件。此外,空的子图也显示在.png文件中,但实际情况并非如此

这是我的密码:

i = -55
j = 55
rows = 5
cols = 5
k = np.ceil((abs(i)+j)/(rows*cols))
cuts = np.arange(i,j,k)
rsn_img = 'rsn_img.png'

fig, axes = plt.subplots(rows, cols, figsize=(15,10))

for r in range(rows):
    for c in range(cols):
        display=plotting.plot_stat_map(rsn_four, display_mode='x', axes=axes[r,c], cut_coords=[cuts[r*cols+c]], threshold=2)
        
        print(f'plotting at index [ {r} , {c}]')
    display.savefig(rsn_img)

这是输出: enter image description here

I应删除未填充的子批次。 提前谢谢你的帮助


Tags: 文件函数inimgforpngdisplaynp
1条回答
网友
1楼 · 发布于 2024-04-27 17:16:46

我假设您知道要打印的图像数N

我会这样写:

i = -55
j = 55
cols = 5
rows = 5
k = np.ceil((abs(i)+j)/(rows*cols))
cuts = np.arange(i,j,k)
N = len(cuts)

fig, axs = plt.subplots(rows, cols)
for ax,cut in zip(axs.flat,cuts):
    display=plotting.plot_stat_map(rsn_four, display_mode='x', axes=ax, cut_coords=cut, threshold=2)
# remove unused axes
for ax in axs.flat[N:]:
    ax.remove()

相关问题 更多 >