光标下的matplotlib值

光标下的matplotlib值,matplotlib,Matplotlib,我正在使用matplotlib.imshow获得二维数组的交互式显示。光标下的x/y坐标显示在窗口的左下角。是否也可以获取光标下数组的值?您只需重新分配ax.format\u-coord。请参阅文档中的 (代码直接取自示例) “”“ 演示如何修改坐标格式化程序以报告图像“z” 给定x和y的最近像素的值 """ 将numpy作为np导入 将matplotlib.pyplot作为plt导入 将matplotlib.cm导入为cm X=10*np.随机.兰德(5,3) 图=plt.图() ax=图添加

我正在使用
matplotlib.imshow
获得二维数组的交互式显示。光标下的x/y坐标显示在窗口的左下角。是否也可以获取光标下数组的值?

您只需重新分配
ax.format\u-coord
。请参阅文档中的

(代码直接取自示例)

“”“
演示如何修改坐标格式化程序以报告图像“z”
给定x和y的最近像素的值
"""
将numpy作为np导入
将matplotlib.pyplot作为plt导入
将matplotlib.cm导入为cm
X=10*np.随机.兰德(5,3)
图=plt.图()
ax=图添加_子批次(111)
ax.imshow(X,cmap=cm.jet,插值='nearest')
numrows,numcols=X.shape
def格式协调(x,y):
col=int(x+0.5)
行=整数(y+0.5)

如果col>=0和col=0以及row我需要一些可以重用的东西,因此我通过一个类封装了解决方案:

#!/usr/bin/env python2
# -*- coding: utf-8 -*-

import numpy as np
class imshow_show_z:

    def __init__(self, ax, z, x, y):
        self.ax = ax
        self.x  = x
        self.y  = y
        self.z  = z
        self.dx = self.x[1] - self.x[0]
        self.dy = self.y[1] - self.y[0]
        self.numrows, self.numcols = self.z.shape
        self.ax.format_coord = self.format_coord
    def format_coord(self, x, y):
        col = int(x/self.dx+0.5)
        row = int(y/self.dy+0.5)
        #print "Nx, Nf = ", len(self.x), len(self.y), "    x, y =", x, y, "    dx, dy =", self.dx, self.dy, "    col, row =", col, row
        xyz_str = ''
        if ((col>=0) and (col<self.numcols) and (row>=0) and (row<self.numrows)):
            zij = self.z[row,col]
            #print "zij =", zij, '  |zij| =', abs(zij)
            if (np.iscomplex(zij)):
                amp = abs(zij)
                phs = np.angle(zij) / np.pi
                if (zij.imag >= 0.0):
                    signz = '+'
                else:
                    signz = '-'
                xyz_str = 'x=' + str('%.4g' % x) + ', y=' + str('%.4g' % y) + ',' \
                            + ' z=(' + str('%.4g' % zij.real) + signz + str('%.4g' % abs(zij.imag)) + 'j)' \
                            + '=' + str('%.4g' % amp) + r'*exp{' + str('%.4g' % phs) + u' π j})'
            else:
                xyz_str = 'x=' + str('%.4g' % x) + ', y=' + str('%.4g' % y) + ', z=' + str('%.4g' % zij)
        else:
            xyz_str = 'x=%1.4f, y=%1.4f'%(x, y)
        return xyz_str

def new_imshow(ax, x, y, z, *args, **kwargs):
    assert(len(x) == z.shape[1])
    assert(len(y) == z.shape[0])
    dx = x[1] - x[0]
    dy = y[1] - y[0]
    if (np.iscomplex(z).any()):
        zabs = abs(z)
    else:
        zabs = z
    # Use this to center pixel around (x,y) values
    extent = (x[0]-dx/2.0, x[-1]+dx/2.0, y[0]-dy/2.0, y[-1]+dy/2.0)
    # Use this to let (x,y) be the lower-left pixel location (upper-left when origin = 'lower' is not used)
    #extent = (x[0]-dx/2.0, x[-1]+dx/2.0, y[0]-dy/2.0, y[-1]+dy/2.0)
    im = ax.imshow(zabs, extent = extent, *args, **kwargs)
    imshow_show_z(ax, z, x, y)
    ax.set_xlim((x[0], x[-1]))
    ax.set_ylim((y[0], y[-1]))
    return im
特点:

  • 可以同时显示浮点值和复数值。对于复数,显示实部+虚部和极性形式
  • 将根据x和y阵列为您设置范围。请注意,matplotlib示例仅在不使用extent关键字时有效
  • 像素围绕其(x,y)位置居中,而不是(x,y)位于左下(或左上)位置

可能与重复相关的toI担心这会是重复的(三份、四份..),但搜索后找不到..不用担心,只是为将来添加了更多google post标记再次阅读此内容,使用该类有点可笑,因为您不保留对它的引用,而是依赖格式\u coord ref来保持对象的活动状态。您可以通过直接执行闭包来运行完全相同的操作。
#!/usr/bin/env python2
# -*- coding: utf-8 -*-

import numpy as np
class imshow_show_z:

    def __init__(self, ax, z, x, y):
        self.ax = ax
        self.x  = x
        self.y  = y
        self.z  = z
        self.dx = self.x[1] - self.x[0]
        self.dy = self.y[1] - self.y[0]
        self.numrows, self.numcols = self.z.shape
        self.ax.format_coord = self.format_coord
    def format_coord(self, x, y):
        col = int(x/self.dx+0.5)
        row = int(y/self.dy+0.5)
        #print "Nx, Nf = ", len(self.x), len(self.y), "    x, y =", x, y, "    dx, dy =", self.dx, self.dy, "    col, row =", col, row
        xyz_str = ''
        if ((col>=0) and (col<self.numcols) and (row>=0) and (row<self.numrows)):
            zij = self.z[row,col]
            #print "zij =", zij, '  |zij| =', abs(zij)
            if (np.iscomplex(zij)):
                amp = abs(zij)
                phs = np.angle(zij) / np.pi
                if (zij.imag >= 0.0):
                    signz = '+'
                else:
                    signz = '-'
                xyz_str = 'x=' + str('%.4g' % x) + ', y=' + str('%.4g' % y) + ',' \
                            + ' z=(' + str('%.4g' % zij.real) + signz + str('%.4g' % abs(zij.imag)) + 'j)' \
                            + '=' + str('%.4g' % amp) + r'*exp{' + str('%.4g' % phs) + u' π j})'
            else:
                xyz_str = 'x=' + str('%.4g' % x) + ', y=' + str('%.4g' % y) + ', z=' + str('%.4g' % zij)
        else:
            xyz_str = 'x=%1.4f, y=%1.4f'%(x, y)
        return xyz_str

def new_imshow(ax, x, y, z, *args, **kwargs):
    assert(len(x) == z.shape[1])
    assert(len(y) == z.shape[0])
    dx = x[1] - x[0]
    dy = y[1] - y[0]
    if (np.iscomplex(z).any()):
        zabs = abs(z)
    else:
        zabs = z
    # Use this to center pixel around (x,y) values
    extent = (x[0]-dx/2.0, x[-1]+dx/2.0, y[0]-dy/2.0, y[-1]+dy/2.0)
    # Use this to let (x,y) be the lower-left pixel location (upper-left when origin = 'lower' is not used)
    #extent = (x[0]-dx/2.0, x[-1]+dx/2.0, y[0]-dy/2.0, y[-1]+dy/2.0)
    im = ax.imshow(zabs, extent = extent, *args, **kwargs)
    imshow_show_z(ax, z, x, y)
    ax.set_xlim((x[0], x[-1]))
    ax.set_ylim((y[0], y[-1]))
    return im
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-5, 10, 100)
y = np.linspace(-2.0, 5, 51)
xx, yy = np.meshgrid(x, y)
Z = np.sin(xx**2 + yy**2) / (xx**2 + yy**2)

fig = plt.figure()
ax = fig.add_subplot(1,1,1)
im = new_imshow(ax, x, y, Z, aspect = 'auto', origin = 'lower', interpolation = 'nearest')
ax.set_xlabel('x')
ax.set_ylabel('y')

plt.show()