Matplotlib:如何使imshow从其他numpy数组中读取x,y坐标?

时间:2017-05-30 11:04:03

标签: python numpy matplotlib imshow

当你想用imshow绘制一个numpy数组时,这就是你通常做的事情:

import numpy as np
import matplotlib.pyplot as plt

A=np.array([[3,2,5],[8,1,2],[6,6,7],[3,5,1]]) #The array to plot

im=plt.imshow(A,origin="upper",interpolation="nearest",cmap=plt.cm.gray_r)
plt.colorbar(im)

这给了我们这个简单的图像: enter image description here

在此图像中,只需从数组中每个值的位置提取 x y 坐标。现在,让我们说A是一个引用某些特定坐标的值数组:

real_x=np.array([[15,16,17],[15,16,17],[15,16,17],[15,16,17]])
real_y=np.array([[20,21,22,23],[20,21,22,23],[20,21,22,23]])

这些价​​值构成了我的理由。 有没有办法强制imshow在A对应的坐标对中分配每个值(real_x,real_y)?

PS:我不是要为基于数组的x和y添加或减去某些内容以使它们匹配 real_x real_y ,但对于 real_x real_y 数组中读取这些值的内容。然后,预期结果是在x轴上具有 real_x 值并且在y轴上具有 real_y 值的图像。

3 个答案:

答案 0 :(得分:10)

设置范围

假设你有

real_x=np.array([15,16,17])
real_y=np.array([20,21,22,23])

您可以将图像范围设置为

dx = (real_x[1]-real_x[0])/2.
dy = (real_y[1]-real_y[0])/2.
extent = [real_x[0]-dx, real_x[-1]+dx, real_y[0]-dy, real_y[-1]+dy]
plt.imshow(data, extent=extent)

更改ticklabels

另一种方法是只更改ticklabels

real_x=np.array([15,16,17])
real_y=np.array([20,21,22,23])
plt.imshow(data)
plt.gca().set_xticks(range(len(real_x)))
plt.gca().set_yticks(range(len(real_x)))
plt.gca().set_xticklabels(real_x)
plt.gca().set_yticklabels(real_y)

答案 1 :(得分:2)

如果我正确理解,这是关于为imshow生成栅格,即给定X-图像坐标和y-值,为imshow生成输入矩阵。我不知道有什么标准功能,所以要实现它

import numpy as np

def to_raster(X, y):
"""
:param X: 2D image coordinates for values y
:param y: vector of scalar or vector values
:return: A, extent
"""
    def deduce_raster_params():
        """
        Computes raster dimensions based on min/max coordinates in X
        sample step computed from 2nd - smallest coordinate values
        """
        unique_sorted = np.vstack((np.unique(v) for v in X.T)).T
        d_min = unique_sorted[0] # x min, y min
        d_max = unique_sorted[-1] # x max, y max
        d_step = unique_sorted[1]-unique_sorted[0] # x, y step
        nsamples = (np.round((d_max - d_min) / d_step) + 1).astype(int)
        return d_min, d_max, d_step, nsamples

    d_min, d_max, d_step, nsamples = deduce_raster_params()
    # Allocate matrix / tensor for raster. Allow y to be vector (e.g. RGB triplets)
    A = np.full((*nsamples, 1 if y.ndim==1 else y.shape[-1]), np.NaN)
    # Compute index for each point in X
    ind = np.round((X - d_min) / d_step).T.astype(int)
    # Scalar/vector values assigned over outer dimension 
    A[list(ind)] = y  # cell id
    # Prepare extent in imshow format
    extent = np.vstack((d_min, d_max)).T.ravel()
    return A, extent

然后可以将其与imshow配合使用:

import matplotlib.pyplot as plt 
A, extent = to_raster(X, y)
plt.imshow(A, extent=extent) 

请注意,由于np.unique()中的排序,所以deduce_raster_params()在O(n * log(n))而不是O(n)中工作-这简化了代码,可能不应该是问题发送给imshow

答案 2 :(得分:1)

对于扩展区方法,要使其起作用,imshow()的参数方面必须为“自动”。