用python画常密度轮廓线,如何使用Matplotlib在极坐标中绘制具有等高线密度线的散点图?...
問題是你只是在轉(zhuǎn)換數(shù)組的邊。通過只轉(zhuǎn)換邊的x和y坐標(biāo),可以有效地轉(zhuǎn)換二維數(shù)組中對(duì)角線的坐標(biāo)。這一行的theta值的范圍非常小,您將該范圍應(yīng)用于整個(gè)網(wǎng)格。在
快速(但不正確)的修復(fù)
在大多數(shù)情況下,您可以將整個(gè)網(wǎng)格(即x和y的二維數(shù)組,生成theta和{}的二維數(shù)組)轉(zhuǎn)換為極坐標(biāo)。在
而不是:H, xedges, yedges = np.histogram2d(x2,y2)
theta_edges, r_edges = CartesianToPolar(xedges[:-1],yedges[:-1])
做類似于:
^{pr2}$
作為一個(gè)完整的例子: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()
但是,您可能會(huì)注意到這看起來有點(diǎn)不正確。這是因?yàn)閍x.contour隱式地假設(shè)輸入數(shù)據(jù)在規(guī)則網(wǎng)格上。我們?cè)诘芽栕鴺?biāo)系下給了它一個(gè)規(guī)則網(wǎng)格,但在極坐標(biāo)系中沒有給它一個(gè)規(guī)則網(wǎng)格。假設(shè)我們?cè)跇O坐標(biāo)系中通過了一個(gè)規(guī)則的網(wǎng)格。我們可以重新取樣,但有更簡單的方法。在
正確的解決方案
要正確繪制二維直方圖,請(qǐng)?jiān)跇O坐標(biāo)空間中計(jì)算直方圖。在
例如,執(zhí)行類似的操作:theta2, r2 = cart2polar(x2,y2)
H, theta_edges, r_edges = np.histogram2d(theta2, r2)
ax2.contour(theta_edges[:-1], r_edges[:-1], H)
作為一個(gè)完整的例子: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()
最后,您可能會(huì)注意到上面的結(jié)果有輕微的變化。這與面向單元格的網(wǎng)格約定(x[0,0], y[0,0]表示單元格的中心)和面向邊緣的網(wǎng)格約定(x[0,0], y[0,0]給出單元格的左下角)有關(guān)。ax.contour希望內(nèi)容以單元格為中心,但您給了它邊緣對(duì)齊的x和y值。在
這只是半個(gè)單元的移位,但如果您想修復(fù)它,請(qǐng)執(zhí)行以下操作: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)
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的用python画常密度轮廓线,如何使用Matplotlib在极坐标中绘制具有等高线密度线的散点图?...的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 我的世界军事村庄种子的代码是什么
- 下一篇: 迷你世界新版鸡怎么引