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

如何为散点图中x=0和x=1位置的两组对应测量点添加连线

配对二值测量数据连线实现方法

核心实现逻辑非常直接:按单个样本为单位,逐根绘制从(0, 该样本第一组测量值)到(1, 该样本第二组测量值)的线段即可,不需要复杂的数据转换。
下面给两种最常用绘图工具的可直接运行的实现代码:

Python Matplotlib 实现

import matplotlib.pyplot as plt
import numpy as np

# 替换成你自己的两组测量数据即可
n_samples = 50
group1 = np.random.randint(0, 2, size=n_samples)  # x=0位置的0/1测量值
group2 = np.random.randint(0, 2, size=n_samples)  # x=1位置的0/1测量值

plt.figure(figsize=(4, 5))
# 给散点加极小幅随机抖动,避免同位置点完全重叠无法识别数量
jitter_strength = 0.03
x_jitter1 = np.random.uniform(-jitter_strength, jitter_strength, n_samples)
y_jitter1 = np.random.uniform(-jitter_strength, jitter_strength, n_samples)
x_jitter2 = np.random.uniform(-jitter_strength, jitter_strength, n_samples)
y_jitter2 = np.random.uniform(-jitter_strength, jitter_strength, n_samples)

plt.scatter(np.zeros(n_samples) + x_jitter1, group1 + y_jitter1, c="#2b8cbe", label="第一组测量")
plt.scatter(np.ones(n_samples) + x_jitter2, group2 + y_jitter2, c="#e34a33", label="第二组测量")

# 逐样本绘制配对连线,加透明度避免线条堆叠糊成块
for y1, y2 in zip(group1, group2):
    plt.plot([0, 1], [y1, y2], c="gray", alpha=0.35)

plt.xticks([0, 1], ["第一组测量", "第二组测量"])
plt.yticks([0, 1])
plt.ylim(-0.15, 1.15)
plt.legend(frameon=False)
plt.show()

R ggplot2 实现

library(ggplot2)
set.seed(123)
n_samples <- 50
# 替换成你自己的测量数据
df <- data.frame(
  sample_id = 1:n_samples,
  measure1 = sample(c(0,1), n_samples, replace = TRUE), # 第一组0/1测量值
  measure2 = sample(c(0,1), n_samples, replace = TRUE)  # 第二组0/1测量值
)

ggplot(df) +
  # 带抖动的散点层
  geom_jitter(aes(x = 0, y = measure1), width = 0.03, height = 0.03, color = "#2b8cbe") +
  geom_jitter(aes(x = 1, y = measure2), width = 0.03, height = 0.03, color = "#e34a33") +
  # 配对连线层,按样本id匹配对应点
  geom_segment(aes(x = 0, xend = 1, y = measure1, yend = measure2, group = sample_id),
               color = "gray", alpha = 0.35) +
  scale_x_continuous(breaks = c(0,1), labels = c("第一组测量", "第二组测量"), expand = c(0.1,0.1)) +
  scale_y_continuous(breaks = c(0,1), limits = c(-0.15, 1.15)) +
  theme_bw()

优化提示

  • 抖动幅度不要设太大,只要让同位置的点能区分开就行,不要破坏x=0/x=1、y=0/y=1的坐标对应关系
  • 如果需要突出测量值的变化情况,可以给不同跃迁类型的线段设置差异化颜色:比如0→1用蓝色、1→0用红色、取值不变的用浅灰色,可读性会高很多
  • 样本量较大时一定要给连线加透明度,否则密集的线条会完全盖住散点,看不出分布规律

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 23:33:35