Python Matplotlib:子地块的居中

Python Matplotlib:子地块的居中,python,matplotlib,Python,Matplotlib,这是我的密码 import matplotlib.pyplot as plt import numpy as np steps = 20 fig = plt.figure() for k in range(steps): ax = fig.add_subplot(1,steps,(k+1)) ax.imshow(np.random.rand(30,30), interpolation="none", cmap="gray") ax.axis("off") fig.tig

这是我的密码

import matplotlib.pyplot as plt
import numpy as np

steps = 20
fig = plt.figure()
for k in range(steps):
    ax = fig.add_subplot(1,steps,(k+1))
    ax.imshow(np.random.rand(30,30), interpolation="none", cmap="gray")
    ax.axis("off")
fig.tight_layout()
plt.subplots_adjust(right=0.97,\
                    left=0.03,\
                    bottom=0.03,\
                    top=0.97,\
                    wspace=0.1,\
                    hspace=0.1)
plt.savefig("test.png", dpi=300, bbox_inches="tight")
plt.close(fig)
这将产生以下输出:

但我真的很想有这样的东西:

只有突出显示的部分。以子地块为中心,子地块周围没有太多空白

我有两个问题,我无法解决与其他类似的帖子有关的子博客,我发现在互联网上。如何使绘图水平和垂直居中?是什么导致绘图不居中?这可能是由
plt.subplot\u adjust()
引起的,我也不太明白。调整这些值有时会导致非直观的结果(在我看来)。如何自动调整
子地块的值,以便对于任意数量的子地块,所有地块都居中,周围没有太多空白?

bbox\u inches=“tight”
自动尝试“猜测”从图形中裁剪多少。如果您想完全控制定位,这可能会导致不期望的结果

现在的主要目标是首先得到所需尺寸的图形

对于粗略估计,数字高度需要为1/steps加上一些空白位置。例如

steps = 20
fig = plt.figure(figsize=(12,(12+3)/steps))
结果很好

import matplotlib.pyplot as plt
import numpy as np

steps = 20
fig = plt.figure(figsize=(12,(12+3)/steps))
for k in range(steps):
    ax = fig.add_subplot(1,steps,(k+1))
    ax.imshow(np.random.rand(30,30), interpolation="none", cmap="gray")
    ax.axis("off")

plt.subplots_adjust(right=0.97,\
                    left=0.03,\
                    bottom=0.03,\
                    top=0.97,\
                    wspace=0.1,\
                    hspace=0.1)
plt.savefig("test.png", dpi=300, facecolor="palegreen")
plt.show()
plt.close(fig)

当然,您可以调整地物大小和子地块参数以精确匹配。例如,从给定的地物宽度开始计算地物高度,同时考虑所有子地块参数和图像的外观(此处更改以使其效果更清晰)

bbox_inches=“tight”
自动尝试“猜测”从图形中裁剪多少。如果您想完全控制定位,这可能会导致不期望的结果

现在的主要目标是首先得到所需尺寸的图形

对于粗略估计,数字高度需要为1/steps加上一些空白位置。例如

steps = 20
fig = plt.figure(figsize=(12,(12+3)/steps))
结果很好

import matplotlib.pyplot as plt
import numpy as np

steps = 20
fig = plt.figure(figsize=(12,(12+3)/steps))
for k in range(steps):
    ax = fig.add_subplot(1,steps,(k+1))
    ax.imshow(np.random.rand(30,30), interpolation="none", cmap="gray")
    ax.axis("off")

plt.subplots_adjust(right=0.97,\
                    left=0.03,\
                    bottom=0.03,\
                    top=0.97,\
                    wspace=0.1,\
                    hspace=0.1)
plt.savefig("test.png", dpi=300, facecolor="palegreen")
plt.show()
plt.close(fig)

当然,您可以调整地物大小和子地块参数以精确匹配。例如,从给定的地物宽度开始计算地物高度,同时考虑所有子地块参数和图像的外观(此处更改以使其效果更清晰)


我将手动重新定位绘图:
用于a在f轴:a.设置位置(x,y,宽度,高度)
。您也可以从初始位置
box=a开始工作。获取位置()
<代码>框将有4个属性,
x0
y0
width
height
。我将手动重新定位绘图:
对于f轴中的a:a.设置位置(x,y,width,height)
。您也可以从初始位置
box=a开始工作。获取位置()
<代码>框将有4个属性,
x0
y0
宽度和高度。