强制颜色图为正方形

Forcing a colormap to be square

我正在使用 matplotlib 库开发 Python,但我遇到了颜色映射尺寸方面的问题。

我有一些目标变量 target 取决于两个变量 xy - 即我的数据 target 是一个矩阵,变量 x 是行和 y 列。我想在关于 xy 的彩色图中表示 target。问题是 x 的值比 y 的值多,因此如果我绘制彩色图,我会得到一个矩形 - 一个相当丑陋的矩形,因为我有更多的 x 值比 y

我宁愿在彩色地图中使用矩形 "pixels" 和方形地图,而不是方形 "pixels" 而是矩形彩色地图 - 或者至少我想比较这两种可视化效果。

我的问题是:如何强制色图为正方形?

这是我当前的代码 - cmap 变量只允许我定义我的自定义色标:

import matplotlib.pyplot as plt
import matplotlib.pyplot as clr

target = ...

cmap = clr.LinearSegmentedColormap.from_list('custom blue', 
                                             ['#DCE6F1','#244162'],
                                             N=128)
plt.matshow(target, cmap=cmap)
plt.colorbar(cmap='custom blue')

你的 matplotlib 版本是多少? 如果它比 1.1.0 更新,那么你可以试试这个:

fig = plt.figure()
ax = fig.add_subplot(111)
ax.imshow(np.random.rand(32, 64), cmap='rainbow', aspect=2)
plt.show()

这会为您提供具有方形图形形状的矩形像素。 您应该将 np.random.rand(32, 64) 替换为您的数据,并定义您喜欢的纵横比。另外,请参考这个post。您可能会对其他解决方案感兴趣。

Andreas 的回答在我的电脑上有效。您可能会看到与您的代码略有不同的结果,因为 imshow() 默认会插入图像,因此图片与 matshow() 相比会有所不同。但是 aspect 参数对两者都有效。所以要么将它提供给 matshow(),要么禁用 imshow() 中的插值:

fig = plt.figure()
ax = fig.add_subplot(111)
ax.matshow(np.random.rand(32, 64), cmap='rainbow', aspect=2)
plt.show()

fig = plt.figure()
ax = fig.add_subplot(111)
ax.imshow(np.random.rand(32, 64), cmap='rainbow', aspect=2, interpolation="None")
plt.show()