用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()

0c80d0f2628fc3e869f8fd1bf20c8f75.png

但是,您可能会注意到这看起来有点不正确。这是因为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()

96361b259c48ae3cb63d07554bd27f7d.png

最后,您可能会注意到上面的结果有轻微的变化。这与面向单元格的网格约定(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)

e8f0bbb56457dd9840daa4e2aecd87bc.png

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值