You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为分组散点图的每个组别分别绘制对应的边际直方图

分组散点图对应分组建边缘直方图实现方法

问题说明

你当前已完成带分组的散点图绘制,边缘直方图默认使用全量数据集统计,需要调整为每组分别生成对应直方图,效果参考下图:
预期绘图示例
你当前的实现效果如下:
当前绘图示例

完整修改代码

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from matplotlib.colors import LinearSegmentedColormap

data= pd.read_csv("data.csv")
x=data['Fe']
y=data['V']
z=data['Discovery']

# 拆分两组数据
x_transit = x[z == 'Transit']
y_transit = y[z == 'Transit']
x_rv = x[z == 'Radial Velocity']
y_rv = y[z == 'Radial Velocity']

# Fixing random state for reproducibility
np.random.seed(19680801)

# definitions for the axes
left, width = 0.1, 0.7
bottom, height = 0.1, 0.7
spacing = 0.05


rect_scatter = [left, bottom, width, height]
rect_histx = [left, bottom + height + spacing, width, 0.2]
rect_histy = [left + width + spacing, bottom, 0.2, height]

# start with a rectangular Figure
fig=plt.figure(figsize=(7, 6))


ax_scatter = plt.axes(rect_scatter)
ax_scatter.tick_params(direction='in', top=True, right=True)
ax_histx = plt.axes(rect_histx)
ax_histx.tick_params(direction='in', labelbottom=True)
ax_histy = plt.axes(rect_histy)
ax_histy.tick_params(direction='in', labelleft=False)

# the function that separates the dots in different classes:
classes = np.zeros( len(x) )
classes[(z == 'Transit')] = 1
classes[(z == 'Radial Velocity')] = 2


# create color map:
colors = ['purple', 'orange']
cm = LinearSegmentedColormap.from_list('custom', colors, N=len(colors))

# the scatter plot:
scatter = ax_scatter.scatter(x, y, c=classes, s=10, cmap=cm, alpha=0.6)
lines, labels = scatter.legend_elements()

# legend with custom labels
labels = [r'Transit', r'Radial Velocity']
legend = ax_scatter.legend(lines, labels,
                    loc="upper left", title="Planetary Discovery Method")
ax_scatter.add_artist(legend)

# now determine nice limits by hand:
binwidth = 0.1
x_min, x_max = -1, 0.7
y_min, y_max = -0.9, 0.9
ax_scatter.set_xlim((x_min, x_max))
ax_scatter.set_ylim((y_min, y_max))

# 补全原代码缺失的bins变量定义,匹配xy轴数值范围
bins_x = np.arange(x_min, x_max + binwidth, binwidth)
bins_y = np.arange(y_min, y_max + binwidth, binwidth)

# 计算两组权重,保持原逻辑用全量占比;如果需要组内归一化,可将分母替换为对应分组的长度
weights_x_transit = np.ones_like(x_transit)/(len(x))
weights_x_rv = np.ones_like(x_rv)/(len(x))
weights_y_transit = np.ones_like(y_transit)/(len(y))
weights_y_rv = np.ones_like(y_rv)/(len(y))

# 分别绘制两组的x轴直方图,颜色和散点分组对应,加透明度避免遮挡
ax_histx.hist(x_transit, bins=bins_x, weights=weights_x_transit, color=colors[0], alpha=0.6, label='Transit')
ax_histx.hist(x_rv, bins=bins_x, weights=weights_x_rv, color=colors[1], alpha=0.6, label='Radial Velocity')

# 分别绘制两组的y轴直方图
ax_histy.hist(y_transit, bins=bins_y, weights=weights_y_transit, orientation='horizontal', color=colors[0], alpha=0.6)
ax_histy.hist(y_rv, bins=bins_y, weights=weights_y_rv, orientation='horizontal', color=colors[1], alpha=0.6)

# 上方直方图可选添加图例
ax_histx.legend()

ax_histx.set_xlim(ax_scatter.get_xlim())
ax_histy.set_ylim(ax_scatter.get_ylim())

#labeling
ax_scatter.set_xlabel('[Fe/H]')
ax_scatter.set_ylabel('[V/H]')
ax_histy.set_xlabel('Relative Dist.')
ax_histx.set_ylabel('Relative Dist.')
plt.show()

关键修改说明

  • 按Discovery字段把x、y数据拆分为Transit和Radial Velocity两个独立子集
  • 补全原代码缺失的bins变量定义,匹配xy轴的数值范围
  • 分两次调用hist方法分别绘制两个分组的直方图,颜色和散点图分组颜色保持一致,添加alpha透明度避免重叠区域遮挡
  • 如需按分组内部归一化分布,只需要把权重计算的分母从全量长度len(x)替换为对应分组的长度len(x_transit)/len(x_rv)即可

内容的提问来源于stack exchange,提问作者Augusto Baldo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 23:27:01