mil*_*boi 3 python matplotlib pandas
我在用 Python 绘制径向热图时遇到问题。我想绘制具有 column 和 的 pandas 数据框中angle的distance值count。的值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
Run Code Online (Sandbox Code Playgroud)
我想离散化这些值,例如,我的箱宽度为 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)
Run Code Online (Sandbox Code Playgroud)
然后我会对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
Run Code Online (Sandbox Code Playgroud)
我还找到了使用groupbyand创建垃圾箱的解决方案,这比使用循环unstack要快得多:for
counts = df.groupby(['distance_bins', 'angle_bins'])['counts'].sum().unstack()
Run Code Online (Sandbox Code Playgroud)
但现在我只想让绘图工作正确。
用于绘图的代码:
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()
Run Code Online (Sandbox Code Playgroud)
这段代码给了我空的直方图。任何帮助,将不胜感激。
您可以使用它np.histogram2d来计算每个垃圾箱的计数。它有一个参数weight=,您可以在其中放置每个条目的给定计数。
热图可以通过ax.pcolormesh极坐标子图直接绘制。需要将角度转换为弧度以匹配极坐标图。
您可以选择使用ax.set_theta_zero_location('N')来告诉零应该去哪里和/或ax.set_theta_direction('clockwise')改变转动方向。
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
# first generate some dummy test data
df = pd.DataFrame()
df['angle'] = np.random.randint(-180, 181, 2000)
df['dist'] = np.random.uniform(0, 20, len(df))
df['counts'] = np.random.randint(1, 5, len(df))
# define the bins
degree_bins = np.arange(-180, 181, 5)
distance_bins = np.arange(0, 20.001, 0.25)
# calculate the 2D histogram
hist, _, _ = np.histogram2d(df['angle'], df['dist'], bins=(degree_bins, distance_bins), weights=df['counts'])
# plot the histogram as a polar heatmap
plt.style.use('dark_background') # this makes the text and grid lines white
fig, ax = plt.subplots(figsize=(10, 10), subplot_kw={'polar': True})
ax.grid(False) # pcolormesh gives an annoying warning when the grid is on
ax.pcolormesh(np.radians(degree_bins), distance_bins, hist.T, cmap='hot')
ax.grid(True)
plt.tight_layout()
plt.show()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
241 次 |
| 最近记录: |