用python画常密度轮廓线,如何使用Matplotlib在极坐标中绘制具有等高线密度线的散点图?...
問題是你只是在轉換數組的邊。通過只轉換邊的x和y坐標,可以有效地轉換二維數組中對角線的坐標。這一行的theta值的范圍非常小,您將該范圍應用于整個網格。在
快速(但不正確)的修復
在大多數情況下,您可以將整個網格(即x和y的二維數組,生成theta和{}的二維數組)轉換為極坐標。在
而不是:H, xedges, yedges = np.histogram2d(x2,y2)
theta_edges, r_edges = CartesianToPolar(xedges[:-1],yedges[:-1])
做類似于:
^{pr2}$
作為一個完整的例子:import numpy as np
import matplotlib.pyplot as plt
def main():
x2, y2 = generate_data()
theta2, r2 = cart2polar(x2,y2)
fig2 = plt.figure()
ax2 = fig2.add_subplot(111, projection="polar")
ax2.scatter(theta2, r2, color='hotpink')
H, xedges, yedges = np.histogram2d(x2,y2)
xedges, yedges = np.meshgrid(xedges[:-1], yedges[:-1])
theta_edges, r_edges = cart2polar(xedges, yedges)
ax2.contour(theta_edges, r_edges, H)
plt.show()
def generate_data():
np.random.seed(2015)
N = 1000
shift_value = -6.
x2 = np.random.randn(N) + shift_value
y2 = np.random.randn(N) + shift_value
return x2, y2
def cart2polar(x,y):
r = np.sqrt(x**2 + y**2)
theta = np.arctan2(y,x)
return theta, r
main()
但是,您可能會注意到這看起來有點不正確。這是因為ax.contour隱式地假設輸入數據在規則網格上。我們在笛卡爾坐標系下給了它一個規則網格,但在極坐標系中沒有給它一個規則網格。假設我們在極坐標系中通過了一個規則的網格。我們可以重新取樣,但有更簡單的方法。在
正確的解決方案
要正確繪制二維直方圖,請在極坐標空間中計算直方圖。在
例如,執行類似的操作:theta2, r2 = cart2polar(x2,y2)
H, theta_edges, r_edges = np.histogram2d(theta2, r2)
ax2.contour(theta_edges[:-1], r_edges[:-1], H)
作為一個完整的例子:import numpy as np
import matplotlib.pyplot as plt
def main():
x2, y2 = generate_data()
theta2, r2 = cart2polar(x2,y2)
fig2 = plt.figure()
ax2 = fig2.add_subplot(111, projection="polar")
ax2.scatter(theta2, r2, color='hotpink')
H, theta_edges, r_edges = np.histogram2d(theta2, r2)
ax2.contour(theta_edges[:-1], r_edges[:-1], H)
plt.show()
def generate_data():
np.random.seed(2015)
N = 1000
shift_value = -6.
x2 = np.random.randn(N) + shift_value
y2 = np.random.randn(N) + shift_value
return x2, y2
def cart2polar(x,y):
r = np.sqrt(x**2 + y**2)
theta = np.arctan2(y,x)
return theta, r
main()
最后,您可能會注意到上面的結果有輕微的變化。這與面向單元格的網格約定(x[0,0], y[0,0]表示單元格的中心)和面向邊緣的網格約定(x[0,0], y[0,0]給出單元格的左下角)有關。ax.contour希望內容以單元格為中心,但您給了它邊緣對齊的x和y值。在
這只是半個單元的移位,但如果您想修復它,請執行以下操作:def centers(bins):
return np.vstack([bins[:-1], bins[1:]]).mean(axis=0)
H, theta_edges, r_edges = np.histogram2d(theta2, r2)
theta_centers, r_centers = centers(theta_edges), centers(r_edges)
ax2.contour(theta_centers, r_centers, H)
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的用python画常密度轮廓线,如何使用Matplotlib在极坐标中绘制具有等高线密度线的散点图?...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 我的世界军事村庄种子的代码是什么
- 下一篇: 迷你世界新版鸡怎么引