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

2024-09-28 22:50:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一份角度表。我想显示一个极柱状图,在这个柱状图中,[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)

现在,我尝试使用以下代码将这些数据绘制成极性柱状图:

^{pr2}$

但我得到的是这张图片: enter image description here

如您所见,条形图没有以正确的角度放置,并且其中一些条彼此重叠,而它们应该是连续的而不重叠。在

我做错什么了?提前谢谢你。在


Tags: the数据代码number列表bewill单元
2条回答

这里只绘制了箱子的中心与每个箱子中出现的角度的数量

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

在注释中,使用弧度而不是度数:

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

相关问题 更多 >