如何在散点图中通过色谱展示多参数的参与情况?
用Matplotlib实现参数参与情况的色谱展示
核心思路
每个(x,y)数据点对应5个参数,我们可以通过颜色区分参数类型、图形面积对应参数权重的方式,直观展示每个点的参数参与占比。常见的实现方式有两种:叠加半透明圆形、饼图标记点。
实现代码(叠加圆形版)
import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm # 给定数据 x_values = np.array([1, 2, 3, 4, 5, 6]) y_values = np.array([4, 6, 3, 5, 7, 6]) information = np.array([ [0.3, 0.5, 0.1, 0.1, 0.2, 0.1], [0.1, 0.2, 0.1, 0.1, 0.1, 0.5], [0.5, 0.1, 0.1, 0.1, 0.5, 0.1], [0.1, 0.1, 0.2, 0.5, 0.1, 0.1], [0.0, 0.1, 0.5, 0.2, 0.1, 0.2]]) # 为5个参数分配差异化颜色 cmap = cm.get_cmap('tab10', 5) param_colors = [cmap(i) for i in range(5)] # 基础尺寸(可根据需求调整) base_size = 1000 plt.figure(figsize=(10, 6)) # 遍历每个数据点,绘制对应参数的叠加圆形 for point_idx in range(len(x_values)): x = x_values[point_idx] y = y_values[point_idx] param_weights = information[:, point_idx] # 计算每个参数对应的圆形面积(与权重成正比) area_ratios = param_weights / np.sum(param_weights) areas = area_ratios * base_size # 叠加半透明圆形,直观展示参数占比 for param_idx, (area, color) in enumerate(zip(areas, param_colors)): plt.scatter(x, y, s=area, color=color, alpha=0.7) # 添加图例 from matplotlib.patches import Patch legend_items = [Patch(facecolor=param_colors[i], label=f'参数{i+1}') for i in range(5)] plt.legend(handles=legend_items, loc='upper right') plt.xlabel('X值') plt.ylabel('Y值') plt.title('数据点参数参与情况色谱展示') plt.grid(True, alpha=0.3) plt.show()
实现代码(饼图标记版,精准展示占比)
如果需要更精确呈现每个参数的占比,可将每个数据点替换为迷你饼图:
import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm # 给定数据(同前) x_values = np.array([1, 2, 3, 4, 5, 6]) y_values = np.array([4, 6, 3, 5, 7, 6]) information = np.array([ [0.3, 0.5, 0.1, 0.1, 0.2, 0.1], [0.1, 0.2, 0.1, 0.1, 0.1, 0.5], [0.5, 0.1, 0.1, 0.1, 0.5, 0.1], [0.1, 0.1, 0.2, 0.5, 0.1, 0.1], [0.0, 0.1, 0.5, 0.2, 0.1, 0.2]]) cmap = cm.get_cmap('tab10', 5) param_colors = [cmap(i) for i in range(5)] base_size = 1000 plt.figure(figsize=(10, 6)) # 遍历每个数据点,绘制饼图标记 for point_idx in range(len(x_values)): x = x_values[point_idx] y = y_values[point_idx] param_weights = information[:, point_idx] # 生成饼图作为标记 pie_parts, _ = plt.pie(param_weights, colors=param_colors, radius=np.sqrt(base_size)/100) plt.scatter(x, y, marker=(pie_parts, 0), s=base_size) # 添加图例 from matplotlib.patches import Patch legend_items = [Patch(facecolor=param_colors[i], label=f'参数{i+1}') for i in range(5)] plt.legend(handles=legend_items, loc='upper right') plt.xlabel('X值') plt.ylabel('Y值') plt.title('数据点参数占比精准展示') plt.grid(True, alpha=0.3) plt.show()
说明
- 两种方式都通过颜色区分不同参数,面积/扇形大小对应参数权重
- 叠加圆形版更适合快速感知参数的相对参与度,饼图标记版则能精确展示占比比例
- 可通过调整
base_size、alpha(透明度)等参数优化展示效果
内容的提问来源于stack exchange,提问作者Mamdud
相关产品推荐
相关产品推荐

