简体   繁体   中英

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

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???

Thanks.

The visualization is just a fancy representation of your data in X , Y and Z .

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:

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 .

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:

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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