파이썬 등고선 맵에서 특정 (x, y) 값을 얻는 방법

Dec 08 2020

의 예 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()

이제 cp라는 등고선 맵을 얻습니다. 등고선 맵 cp에서 점 (x, y)의 z 값을 어떻게 얻을 수 있습니까 ???

감사.

답변

2 PatrickArtner Dec 08 2020 at 14:45

시각화는 X, Y및 의 데이터를 멋지게 표현한 것입니다 Z.

이미 계산 된 값이 있으므로 간단히 조회 할 수 있습니다.

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")

산출:

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

당신이 특정 조회하려면 x,y- 값을,로 닫히고 인덱스를 찾을 수 xlistylist으로부터 그 값을 얻을 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") 

산출:

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

그래프에서 직접 읽은 후에도 여전히 그래프에서 포인트를 추출하는 방법을 시도해보십시오.