如何在matplotlib中绘制极性hist2d/hexbin? [英] How to draw polar hist2d/hexbin in matplotlib?

查看:139
本文介绍了如何在matplotlib中绘制极性hist2d/hexbin?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个随机向量(随机长度和随机角度),并希望通过hist2dhexbin绘制其近似PDF(概率密度函数).不幸的是,它们似乎不适用于极坐标图,以下代码无法产生任何结果:

I have a random vector (random length and random angle) and would like to plot its approximate PDF (probability density function) via hist2d or hexbin. Unfortunately they seems not to work with polar plots, the following code yields nothing:

import numpy as np
import matplotlib.pyplot as plt

# Generate random data:
N = 1024
r = .5 + np.random.normal(size=N, scale=.1)
theta = np.pi / 2 + np.random.normal(size=N, scale=.1)

# Plot:
ax = plt.subplot(111, polar=True)
ax.hist2d(theta, r)
plt.savefig('foo.png')
plt.close()

我希望它看起来像这样: pylab_examples示例代码:hist2d_demo.py 仅在极坐标中.迄今为止最接近的结果是彩色散点图为

I would like it to look like this: pylab_examples example code: hist2d_demo.py only in polar coordinates. The closest result so far is with colored scatter plot as adviced here:

import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import gaussian_kde

# Generate random data:
N = 1024
r = .5 + np.random.normal(size=N, scale=.1)
theta = np.pi / 2 + np.random.normal(size=N, scale=.1)

# Plot:
ax = plt.subplot(111, polar=True)

# Using approach from:
# https://stackoverflow.com/questions/20105364/how-can-i-make-a-scatter-plot-colored-by-density-in-matplotlib
theta_r = np.vstack([theta,r])
z = gaussian_kde(theta_r)(theta_r)

ax.scatter(theta, r, c=z, s=10, edgecolor='')

plt.savefig('foo.png')
plt.close()

第二版代码中的图片

是否有更好的方法使其更像由hist2d生成的真实PDF? 这个问题似乎是相关的(生成的图像符合预期),但看起来很杂乱.

Is there a better way to make it more like real PDF generated with hist2d? This question seems to be relevant (the resulting image is as expected), but it looks messy.

推荐答案

使用结果:

请注意,直方图尚未通过bin的面积进行归一化,在极坐标中该面积不是恒定的.靠近原点,垃圾箱很小,因此使用其他网格划分可能会更好.

Note that the histogram is not yet normalized by the area of the bin, which is not constant in polar coordinates. Close to the origin, the bins are pretty small, so some other kind of meshing might be better.

这篇关于如何在matplotlib中绘制极性hist2d/hexbin?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆