gpt4 book ai didi

python - matplotlib imshow 固定方面和垂直颜色条匹配主轴高度

转载 作者:太空宇宙 更新时间:2023-11-03 11:29:11 27 4
gpt4 key购买 nike

我需要绘制一个带有“温度图”值的网格,目前我正在使用带有颜色图的 imshow。这在 Matplotlib overview 中有描述。 ,所以我修改了示例以强制自定义图形方面:

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np

plt.figure()
ax = plt.gca()
im = ax.imshow(np.arange(100).reshape((10,10)), aspect=0.5)

# create an axes on the right side of ax. The width of cax will be 5%
# of ax and the padding between cax and ax will be fixed at 0.05 inch.
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)

plt.colorbar(im, cax=cax)

plt.savefig("test.png")

但结果不是我想要的,颜色条高于主轴:test

有趣的是,当颜色图是水平的时,它会被适本地缩放:

cax = divider.append_axes("bottom", size="5%", pad=0.05)
plt.colorbar(im, cax=cax, orientation="horizontal")

horizontal

最佳答案

此处发生的是您将 0.5 的宽高比应用于 imshow 图像。这会将图像的垂直范围除以 2,而颜色条保持原始范围。我看到 2 个解决方案

您可以使用以下方式手动设置颜色条的大小:

cax = fig.add_axes([0.85, 0.3, 0.04, 0.4])

...或者您可以将 aspect 应用于 cax 以保持其 y 维度与图像一致。在您将大小设置为 5% 的情况下,设置 aspect=1 将为您提供原始垂直范围为 1/20 的图像。要获得图像的 1/2,请将纵横比设置为 20*0.5=10。您可以为纵横比创建一个变量,如果您想尝试更改图形的纵横比,颜色条将随之变化。

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np

fig = plt.figure()
ax = plt.gca()
im = ax.imshow(np.arange(100).reshape((10,10)), aspect=0.5)

# create an axes on the right side of ax. The width of cax will be 5%
# of ax and the padding between cax and ax will be fixed at 0.05 inch.
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05, aspect=10)
#cax = fig.add_axes([0.85, 0.3, 0.04, 0.4])
plt.colorbar(im, cax=cax)

plt.show()

关于python - matplotlib imshow 固定方面和垂直颜色条匹配主轴高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26563858/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com