更改matplotlib imshow()图轴上的值

ato*_*3ls 69 python numpy matplotlib

说我有一些输入数据:

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))
Run Code Online (Sandbox Code Playgroud)

我可以用它绘图imshow():

plt.imshow(hist,cmap='Reds')
Run Code Online (Sandbox Code Playgroud)

得到:

在此输入图像描述

但是,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
Run Code Online (Sandbox Code Playgroud)

ax.set_xticklabels(edges)
...
# this labels the axis but does not centre around the mean:
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

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

Rut*_*ies 109

我会尽量避免在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
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 值得注意的是,这里使用了"interpolation ="none"`,这是一种更准确的真实数据表示. (14认同)
  • 最有用的答案; 我用它来制作两个变量函数的颜色图(即地震数据).我还在imshow()中添加了"aspect ='auto'"选项,这样我就可以"拉伸和挤压"地震显示. (4认同)

小智 11

I had a similar problem and google was sending me to this post. My solution was a bit different and less compact, but hopefully this can be useful to someone.

使用 matplotlib.pyplot.imshow 显示图像通常是显示 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
Run Code Online (Sandbox Code Playgroud)