python - 如何使用 Matplotlib 在极坐标中绘制具有等高线密度线的散点图?

标签 python matplotlib scatter-plot polar-coordinates

我正在尝试在极坐标 中绘制散点图,等高线叠加到点云上。我知道如何使用 numpy.histogram2d 在笛卡尔坐标系中做到这一点:

# Simple case: scatter plot with density contours in cartesian coordinates

import matplotlib.pyplot as pl
import numpy as np

np.random.seed(2015)
N = 1000
shift_value = -6.

x1 = np.random.randn(N) + shift_value
y1 = np.random.randn(N) + shift_value

fig, ax = pl.subplots(nrows=1,ncols=1)

ax.scatter(x1,y1,color='hotpink')

H, xedges, yedges = np.histogram2d(x1,y1)
extent = [xedges[0],xedges[-1],yedges[0],yedges[-1]]
cset1 = ax.contour(H,extent=extent)

# Modify xlim and ylim to be a bit more consistent with what's next
ax.set_xlim(xmin=-10.,xmax=+10.)
ax.set_ylim(ymin=-10.,ymax=+10.)

输出在这里:

correct_output_cartesian

但是,当我尝试将我的代码转置到极坐标时,我得到了扭曲的等高线。这是我的代码和生成的(错误的)输出:

# Case with polar coordinates; the contour lines are distorted

np.random.seed(2015)
N = 1000
shift_value = -6.

def CartesianToPolar(x,y):
    r = np.sqrt(x**2 + y**2)
    theta = np.arctan2(y,x)

    return theta, r

x2 = np.random.randn(N) + shift_value
y2 = np.random.randn(N) + shift_value

theta2, r2 = CartesianToPolar(x2,y2)

fig2 = pl.figure()
ax2 = pl.subplot(projection="polar")
ax2.scatter(theta2, r2, color='hotpink')

H, xedges, yedges = np.histogram2d(x2,y2)


theta_edges, r_edges = CartesianToPolar(xedges[:-1],yedges[:-1])
ax2.contour(theta_edges, r_edges,H)

错误的输出在这里:

wrong_output_polar

有什么办法可以让等高线的比例合适吗?

编辑以解决评论中提出的建议。

EDIT2:有人建议该问题可能与 this question 重复.尽管我认识到这些问题是相似的,但我的问题专门处理在散点图上绘制点的密度等高线。另一个问题是关于如何绘制指定数量的等高线水平以及点的坐标。

最佳答案

问题是您只是在转换数组的边缘。通过仅转换边的 x 和 y 坐标,您可以有效地转换二维数组中对角线的坐标。此行的 theta 值范围非常小,您将该范围应用于整个网格。

快速(但不正确)的修复

在大多数情况下,您可以转换整个网格(即 xy 的二维数组,生成 thetar) 到极坐标。

代替:

H, xedges, yedges = np.histogram2d(x2,y2)
theta_edges, r_edges = CartesianToPolar(xedges[:-1],yedges[:-1])

做类似的事情:

H, xedges, yedges = np.histogram2d(x2,y2)
xedges, yedges = np.meshgrid(xedges[:-1],yedges[:-1]
theta_edges, r_edges = CartesianToPolar(xedges, yedges)

作为一个完整的例子:

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

enter image description here

但是,您可能会注意到这看起来有点不正确。这是因为 ax.contour 隐含地假设输入数据位于规则网格上。我们给它一个笛卡尔坐标系的规则网格,但不是极坐标系的规则网格。假设我们已经将极坐标中的规则网格传递给它。我们可以对网格重新采样,但还有更简单的方法。

正确的解决方案

要正确绘制 2D 直方图,请计算极空间中的直方图。

例如,做类似的事情:

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

enter image description here

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

enter image description here

关于python - 如何使用 Matplotlib 在极坐标中绘制具有等高线密度线的散点图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30713586/

相关文章:

python - 如何更改子图中不同线条的线条颜色

python-3.x - 按月份对字典中的字典进行排序

r - 向 ggplot2 散点图添加文本标签

r - 如何将我的散点图转换为正确的散点图?

python - 使用正则表达式从 Python 文本中提取第一个日期

python - WLS2 UBUNTU : npm ERR! gyp 错误!堆栈错误 : Can't find Python executable "python", 您可以设置 PYTHON 环境变量。和更多

python - Django - 跨查询集的 DatetimeField 时间聚合

python - Pandas 数据框按日期排序,然后分配字母 A-Z

python - 带 basemap 的空图

python - 如何在一个散点图上将多个数据集绘制在各自的列上