如何使用Python和pyplot将标准直方图数据绘制成极坐标直方图?

4

我有一个角度的列表,想要显示一个极坐标直方图,其中[0°, 360°)值范围被分成相等的箱子,并显示角度列表中有多少个值落入每个箱子。我使用以下代码获取直方图数据(我已经检查了它是正确的):

bins_number = 8 # the [0, 360) interval will be subdivided into this number of equal bins
bins = np.linspace(0.0, 360.0, bins_number + 1)
n, _, _ = plt.hist(angles, bins)

现在,我已经尝试使用以下代码将这些数据绘制成极坐标直方图:
plt.clf()
width = 2 * np.pi / bins_number
ax = plt.subplot(1, 1, 1, projection='polar')
bars = ax.bar(bins[:bins_number], n, width=width, bottom=0.0)
for bar in bars:
    bar.set_alpha(0.5)
plt.show()

但我得到的结果如下图所示: enter image description here

正如您所看到的,条形图的角度不正确,有些条形图彼此重叠,而它们应该是相邻的且不重叠的。

我做错了什么?提前感谢您的帮助。


3
尝试使用弧度,乘以2π并除以360°。 - berna1111
2个回答

3

如评论所述,应使用弧度而非角度:

import numpy as np
import matplotlib.pyplot as plt

n_numbers = 100
bins_number = 8  # the [0, 360) interval will be subdivided into this
# number of equal bins
bins = np.linspace(0.0, 2 * np.pi, bins_number + 1)
angles = 2 * np.pi * np.random.rand(n_numbers)
n, _, _ = plt.hist(angles, bins)

plt.clf()
width = 2 * np.pi / bins_number
ax = plt.subplot(1, 1, 1, projection='polar')
bars = ax.bar(bins[:bins_number], n, width=width, bottom=0.0)
for bar in bars:
    bar.set_alpha(0.5)
plt.show()

enter image description here


1

在这里,我们只是绘制每个箱子内角度出现次数与箱子中心的关系图。

import numpy as np
import matplotlib.pyplot as plt

degrees = np.random.randint(0, 360, size=200)
radians = np.deg2rad(degrees)

bin_size = 20
a , b=np.histogram(degrees, bins=np.arange(0, 360+bin_size, bin_size))
centers = np.deg2rad(np.ediff1d(b)//2 + b[:-1])

fig = plt.figure(figsize=(10,8))
ax = fig.add_subplot(111, projection='polar')
ax.bar(centers, a, width=np.deg2rad(bin_size), bottom=0.0, color='.8', edgecolor='k')
ax.set_theta_zero_location("N")
ax.set_theta_direction(-1)
plt.show()

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接