在 python 中绘制径向热图

问题描述 投票:0回答:0

我在用 Python 绘制径向热图时遇到问题。我想绘制具有

angle
distance
count
列的pandas数据框的值。
angle
的值是从 -180 到 180。
distance
是从 0 到 20 的值,
count
表示该对(角度,距离)的值计数。

一个数据框的例子

df.head(10)

    angle   dist    counts
0   -180.0  0.64    1
1   -180.0  0.67    1
2   -180.0  0.68    1
3   -180.0  0.72    1
4   -180.0  0.75    2
5   -180.0  0.76    2
6   -180.0  0.78    1
7   -180.0  0.79    4
8   -180.0  0.80    1
9   -180.0  0.82    2

我想离散化这些值,例如,我有宽度为 5 度、距离为 0.25 的箱子。在单元格中,汇总这些值的计数,然后绘制为径向热图。

现在我是这样工作的,我会定义一个模拟矩阵的 pandas 数据框,其列的度数从 -180 到 180 (-180, -175, ..., 175, 180),索引值从 0 到20,步长为 0.25 (0, 0.25, ..., 19.75, 20)

degree_bins = np.array([x for x in range(-180, 181, 5)])
distance_bins = np.array([x*0.25 for x in range(0, 81)])
round_bins = pd.DataFrame(0, index=distance_bins, columns=degree_bins)

然后我会总结

count
值:

for row in tot.iterrows():
    _, value = row
    degree = value["angle"]
    distance = value["distance"]
    count = value["counts"]
    degree_bin = np.digitize([degree], degree_bins)[0]-1
    distance_bin = np.digitize([distance], distance_bins)[0]-1
    round_bins.iloc[distance_bin, degree_bin] += count

我还找到了使用

groupby
unstack
创建垃圾箱的解决方案,这比使用
for
循环快得多:

counts = df.groupby(['distance_bins', 'angle_bins'])['counts'].sum().unstack()

但现在我只想让绘图工作正确。

用于绘图的代码:

n = len(degree_bins)
m = len(distance_bins)

rad = np.linspace(0, 20.25, m)
a = np.linspace(0, 2 * np.pi, n)
r, th = np.meshgrid(rad, a)
z = round_bins.to_numpy().T
plt.figure(figsize=(20, 20))
plt.subplot(projection="polar")
plt.pcolormesh(th, r, z, cmap='jet')
plt.plot(a, r, ls='none', color='k')
plt.grid()
plt.colorbar()

这段代码给我空的直方图。任何帮助将不胜感激。

python pandas matplotlib
© www.soinside.com 2019 - 2024. All rights reserved.