更改 matplotlib imshow() 图形轴上的值

Posted

技术标签:

【中文标题】更改 matplotlib imshow() 图形轴上的值【英文标题】:Change values on matplotlib imshow() graph axis 【发布时间】:2013-09-12 19:37:10 【问题描述】:

假设我有一些输入数据:

data = np.random.normal(loc=100,scale=10,size=(500,1,32))
hist = np.ones((32,20)) # initialise hist
for z in range(32):
    hist[z],edges = np.histogram(data[:,0,z],bins=np.arange(80,122,2))

我可以使用imshow() 绘制它:

plt.imshow(hist,cmap='Reds')

得到:

但是,x 轴值与输入数据不匹配(即平均值 100,范围从 80 到 122)。因此,我想更改 x 轴以显示 edges 中的值。

我试过了:

ax = plt.gca()
ax.set_xlabel([80,122]) # range of values in edges
...
# this shifts the plot so that nothing is visible

ax.set_xticklabels(edges)
...
# this labels the axis but does not centre around the mean:

关于如何更改轴值以反映我正在使用的输入数据的任何想法?

【问题讨论】:

使用pcolor 而不是imshow,正如answer 中提到的那样。 【参考方案1】:

我遇到了类似的问题,谷歌将我发送到这篇文章。我的解决方案有点不同,不太紧凑,但希望这对某人有用。

使用 matplotlib.pyplot.imshow 显示图像通常是显示 2D 数据的快速方法。但是,默认情况下,这会用像素数标记轴。如果您正在绘制的 2D 数据对应于由数组 x 和 y 定义的某个统一网格,那么您可以使用 matplotlib.pyplot.xticks 和 matplotlib.pyplot.yticks 使用这些数组中的值标记 x 和 y 轴。这些会将与实际网格数据相对应的一些标签与轴上的像素计数相关联。这样做比使用 pcolor 之类的东西要快得多。

这是对您的数据的尝试:

import matplotlib.pyplot as plt

# ... define 2D array hist as you did

plt.imshow(hist, cmap='Reds')
x = np.arange(80,122,2) # the grid to which your data corresponds
nx = x.shape[0]
no_labels = 7 # how many labels to see on axis x
step_x = int(nx / (no_labels - 1)) # step between consecutive labels
x_positions = np.arange(0,nx,step_x) # pixel count at label position
x_labels = x[::step_x] # labels you want to see
plt.xticks(x_positions, x_labels)
# in principle you can do the same for y, but it is not necessary in your case

【讨论】:

【参考方案2】:

如果可能,我会尽量避免更改xticklabels,否则如果您使用附加数据过度绘制直方图,它会变得非常混乱。

定义网格的范围可能是最好的,使用imshow 可以通过添加extent 关键字来完成。这样轴就会自动调整。如果您想更改标签,我会使用 set_xticks 和一些格式化程序。直接更改标签应该是最后的手段。

fig, ax = plt.subplots(figsize=(6,6))

ax.imshow(hist, cmap=plt.cm.Reds, interpolation='none', extent=[80,120,32,0])
ax.set_aspect(2) # you may also use am.imshow(..., aspect="auto") to restore the aspect ratio

【讨论】:

还值得注意的是,这里使用了interpolation="none",这是对真实数据的更准确表示。 一个最有用的答案;我用它来制作两个变量(即地震数据)的函数的彩色图。我还在 imshow() 中添加了选项“aspect='auto'”,以便我可以“拉伸和挤压”地震显示。

以上是关于更改 matplotlib imshow() 图形轴上的值的主要内容,如果未能解决你的问题,请参考以下文章

Matplotlib:quiver 和 imshow 叠加,如何设置两个颜色条?

将 cv2.imshow() 与 matplotlib plt.show() 实时结合

如何以交互方式更新 matplotlib imshow() 窗口?

如何以交互方式更新 matplotlib imshow() 窗口?

matplotlib:创建新图形并保存到文件

设置 Matplotlib 颜色条大小以匹配图形