在等高线图中显示数组值

2024-04-24 17:33:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数组,其中包含的值,我用X和Y作为坐标轴,使用

plt.contourf(X,Y,A)

我想知道,当我将光标悬停在绘图的某个(X,Y)点上时,如何获得A的值,或者在我查看绘图时在任何点获得值的任何其他替代方法。你知道吗

非常感谢!你知道吗


Tags: 方法绘图plt数组光标坐标轴contourf
1条回答
网友
1楼 · 发布于 2024-04-24 17:33:15

必须使用axis对象的format_coord属性:

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)
A = np.arange(25).reshape(5,5)
X = np.arange(5)
Y = np.arange(5)
X,Y = np.meshgrid(X,Y)
plt.contourf(X,Y,A)

nrows, ncols = A.shape
def format_coord(x, y):
    i = int(x)
    j = int(y)
    if j >= 0 and j < ncols and i >= 0 and i < nrows: 
        return "A[{0}, {1}] = {2}".format(i, j, A[i][j])
    else: return "[{0} {1}]".format(i, j)

ax.format_coord = format_coord
plt.show()

示例:

enter image description here

相关问题 更多 >