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

合并温度DataFrame,绘制单组分色箱线图并展示散点

解决方案

要实现同时展示分组箱线图、不同颜色的单个数据点,你可以结合Seaborn的boxplot和stripplot(或swarmplot)来完成,核心是利用hue参数区分组别,并通过dodge=True避免散点与箱线重叠。以下是完整实现步骤:

1. 完善数据生成(补充21世纪数据)

首先补充生成21世纪的温度数据,我们让它的中位数略高于20世纪,以便观察差异:

import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

def generate(median=20, err=1, outlier_err=25, size=100, outlier_size=10):
    errs = err * np.random.rand(size) * np.random.choice((-5, 5), size)
    data = median + errs

    lower_errs = outlier_err * np.random.rand(outlier_size)
    lower_outliers = median - err - lower_errs

    upper_errs = outlier_err * np.random.rand(outlier_size)
    upper_outliers = median + err + upper_errs

    data = np.round(np.concatenate((data, lower_outliers, upper_outliers)))
    np.random.shuffle(data)

    return data

# 生成20世纪数据
data_20th = pd.DataFrame(generate(), columns=['temp'])
data_20th['year'] = '20th Century'

# 生成21世纪数据(中位数设为22,体现温度上升)
data_21st = pd.DataFrame(generate(median=22), columns=['temp'])
data_21st['year'] = '21st Century'

# 合并数据
full_data = pd.concat([data_20th, data_21st], ignore_index=True)

2. 绘制箱线图+散点图

使用boxplot绘制箱线,再用stripplot叠加单个数据点,通过hue参数指定组别颜色,dodge=True确保散点与对应箱线对齐:

# 设置绘图风格
sns.set_style("whitegrid")
plt.figure(figsize=(8, 6))

# 绘制箱线图,hue区分组别,palette指定颜色
box = sns.boxplot(
    x='year', 
    y='temp', 
    hue='year', 
    data=full_data,
    palette={'20th Century': '#3498db', '21st Century': '#e74c3c'},
    boxprops={'alpha': 0.7},  # 箱线透明度
    showfliers=False  # 不显示箱线自带的异常值点,改用stripplot展示所有点
)

# 绘制散点图,dodge=True让散点与箱线对齐,jitter添加随机偏移避免重叠
stripplot = sns.stripplot(
    x='year', 
    y='temp', 
    hue='year', 
    data=full_data,
    palette={'20th Century': '#3498db', '21st Century': '#e74c3c'},
    dodge=True,
    jitter=0.2,
    size=4,
    alpha=0.6
)

# 合并重复图例(boxplot和stripplot会生成两份图例)
handles, labels = box.get_legend_handles_labels()
plt.legend(handles[:2], labels[:2], title='Century')

# 添加标题和标签
plt.title('Temperature Distribution: 20th vs 21st Century', fontsize=14)
plt.xlabel('Century', fontsize=12)
plt.ylabel('Temperature (°C)', fontsize=12)

plt.show()

关键说明

  • showfliers=False:关闭箱线图自带的异常值点,避免与手动添加的散点重复。
  • dodge=True:确保散点与对应组的箱线对齐,不会跨组重叠。
  • jitter=0.2:给散点添加少量随机水平偏移,避免大量点重叠在一起。
  • palette:手动指定两组的颜色,确保箱线和散点颜色一致。

这样生成的图既能清晰展示两个世纪的温度分布箱线,又能通过不同颜色的散点看到每个数据点的位置,方便判断21世纪的温度是否处于20世纪的异常值范围。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 23:25:24