【问题标题】:How do I plot a standard histogram data to a polar histogram using Python and pyplot?如何使用 Python 和 pyplot 将标准直方图数据绘制为极坐标直方图?
【发布时间】:2018-07-23 23:42:43
【问题描述】:

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

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

但我得到的显示在这张图片中:

如您所见,条形的放置角度不正确,其中一些相互重叠,而它们应该都是连续的而不重叠。

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

【问题讨论】:

  • 尝试使用radians,乘以2pi再除以360°。

标签: python matplotlib histogram polar-coordinates


【解决方案1】:

如评论中所述,使用弧度而不是度数:

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

【讨论】:

    【解决方案2】:

    这里只是绘制 bin 中心与每个 bin 中角度出现次数的关系

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-29
      • 1970-01-01
      • 2021-12-09
      相关资源
      最近更新 更多