请教如何复刻高聚合度红色Scatterplot可视化风格
问题
我想重现目标图中的散点图可视化风格,当前制作的散点图会显示所有数据点,而我想要实现活动密集区域显示更大的深红色圆圈、活动稀疏区域显示浅色小圆圈的效果。我认为需要设置阈值来选择性展示数据点,避免全部显示,恳请指导如何实现类似目标图的可视化效果。
当前效果:
目标效果:
我的实现代码:
from typing import List, Tuple, Literal import seaborn as sns def plot_cumulative_heatmap(positions: List[Tuple[float, float]], map_name: str = "de_mirage", map_type: str = "original", dark: bool = False, titel: str = "Counter-Terrorist Attacking", isPistol: str = "Pistol Round") -> Literal[True]: heatmap_fig, heatmap_axes = plot_map(map_name=map_name, map_type=map_type, dark=dark) heatmap_data = [] for position in positions: x, y = position heatmap_data.append((x, y)) # Extract data for plotting x, y = zip(*heatmap_data) sns.scatterplot(x=x, y=y, color='red', s=5, ax=heatmap_axes, alpha=0.5) heatmap_axes.set_title(f"{titel}\nTotal Positions: {len(positions)}\n{isPistol}", fontsize=14, weight="bold") heatmap_axes.get_xaxis().set_visible(False) heatmap_axes.get_yaxis().set_visible(False) print("Heatmap saved.") return True
解决方案
要实现目标图的效果,核心是根据区域的数据点密度调整点的大小和颜色,而非直接显示所有原始点。以下是具体实现方案:
核心思路
- 对地图坐标进行网格分箱,统计每个网格内的点数(即密度)
- 基于密度映射点的大小(密度越高点越大)和颜色(密度越高颜色越深)
- 过滤无数据的网格,只显示有数据的区域
修改后的代码实现
from typing import List, Tuple, Literal import numpy as np import matplotlib.pyplot as plt import matplotlib.colors as mcolors def plot_cumulative_heatmap(positions: List[Tuple[float, float]], map_name: str = "de_mirage", map_type: str = "original", dark: bool = False, titel: str = "Counter-Terrorist Attacking", isPistol: str = "Pistol Round") -> Literal[True]: heatmap_fig, heatmap_axes = plot_map(map_name=map_name, map_type=map_type, dark=dark) # 提取坐标数据并转为numpy数组 x, y = zip(*positions) x = np.array(x) y = np.array(y) # 1. 分箱统计每个网格的点数(密度) bins = 50 # 网格数量,值越大精度越高,可根据地图尺寸调整 counts, x_edges, y_edges = np.histogram2d(x, y, bins=bins) # 计算每个网格的中心坐标(用于绘制点) x_centers = (x_edges[:-1] + x_edges[1:]) / 2 y_centers = (y_edges[:-1] + y_edges[1:]) / 2 x_mesh, y_mesh = np.meshgrid(x_centers, y_centers) # 展平数据并过滤无数据的网格 counts_flat = counts.flatten() x_flat = x_mesh.flatten() y_flat = y_mesh.flatten() mask = counts_flat > 0 x_filtered = x_flat[mask] y_filtered = y_flat[mask] density = counts_flat[mask] # 2. 设置大小和颜色映射 size = np.sqrt(density) * 12 # 用平方根缩放避免大密度点尺寸过大,系数可调整 norm = mcolors.Normalize(vmin=density.min(), vmax=density.max()) colors = plt.cm.Reds(norm(density)) # Reds色系实现从浅到深的红色渐变 # 3. 绘制密度散点图 heatmap_axes.scatter(x_filtered, y_filtered, s=size, color=colors, alpha=0.8) heatmap_axes.set_title(f"{titel}\nTotal Positions: {len(positions)}\n{isPistol}", fontsize=14, weight="bold") heatmap_axes.get_xaxis().set_visible(False) heatmap_axes.get_yaxis().set_visible(False) print("Heatmap saved.") return True
参数调整建议
bins:控制网格精细度,值越大网格越密,显示的点越多;值越小网格越粗,点越少size的缩放系数:调整点的最大/最小尺寸,让显示效果匹配目标图- 颜色可替换为
plt.cm.Reds_r反转色系,或自定义渐变范围
内容的提问来源于stack exchange,提问作者Nick
相关产品推荐
相关产品推荐

