简体   繁体   English

如何在 python 轮廓 map 中获得特定 (x,y) 的值

[英]How can get a value of specific (x,y) in python contour map

A example in https://www.tutorialspoint.com/matplotlib/matplotlib_contour_plot.htm https 中的一个示例://www.tutorialspoint.com/matplotlib/matplotlib_contour_plot.htm

import numpy as np
import matplotlib.pyplot as plt
xlist = np.linspace(-3.0, 3.0, 100)
ylist = np.linspace(-3.0, 3.0, 100)
X, Y = np.meshgrid(xlist, ylist)
Z = np.sqrt(X**2 + Y**2)
fig,ax=plt.subplots(1,1)
cp = ax.contourf(X, Y, Z)
fig.colorbar(cp) # Add a colorbar to a plot
ax.set_title('Filled Contours Plot')
#ax.set_xlabel('x (cm)')
ax.set_ylabel('y (cm)')
plt.show()

Now, we get a contour map named cp, how can I get the z value of point (x,y) in the contour map cp???现在,我们得到一个名为cp的轮廓map,我怎样才能得到轮廓map cp中点(x,y)的z值?

Thanks.谢谢。

The visualization is just a fancy representation of your data in X , Y and Z .可视化只是XYZ中数据的精美表示。

You already have the values calulated, you can simply look them up:您已经计算了值,您可以简单地查找它们:

import numpy as np
import matplotlib.pyplot as plt

xlist = np.linspace(-3.0, 3.0, 100)
ylist = np.linspace(-3.0, 3.0, 100)
X, Y = np.meshgrid(xlist, ylist)
Z = np.sqrt(X**2 + Y**2)

x = 42  # xlist has 100 entries
y = 21  # ylist has 100 entries

print(f"x at pos {x} is {xlist[x]}", f"y at pos {y} is {ylist[y]}",
      f"z value at that place is {Z[x][y]}", sep="\n")

Output: Output:

x at pos 42 is -0.4545454545454546
y at pos 21 is -1.7272727272727273
z value at that place is 1.7860802458535001

If you want to look up a certain x,y -value, find the closes index into xlist and ylist and get its value from Z .如果要查找某个x,y值,请在xlistylist中找到 closes 索引,并从Z获取其值。

xv = 1.2
yv = -0.7

x_pos = min(p for p in range(100) if xlist[p] >= xv) # could do something better
y_pos = min(p for p in range(100) if ylist[p] >= yv) # using np.where or such

# or use any other metric to get the "closest" point, f.e.
# d_x, x_pos = min( (abs(v), p) for p,v in enumerate(xlist - np.array([xv]*100)))
# d_y, y_pos = min( (abs(v), p) for p,v in enumerate(ylist - np.array([yv]*100)))

print(f"x at pos {x_pos} is {xlist[x_pos]} (looking for {xv})",
      f"y at pos {y_pos} is {ylist[y_pos]} (looking for {yv})",
      f"z value at that place is {Z[x_pos][y_pos]}", sep="\n") 

Output: Output:

x at pos 70 is 1.2424242424242422 (looking for 1.2)
y at pos 38 is -0.6969696969696968 (looking for -0.7)
z value at that place is 1.4245647604294736

# x at pos 69 is 1.1818181818181817 (looking for 1.2)
# y at pos 38 is -0.6969696969696968 (looking for -0.7)
# z value at that place is 1.3720280512329417

If you are still after directly reading from the graph, try: How to extract points from a graph?如果您仍然在直接从图形中读取,请尝试: 如何从图形中提取点?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM