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

如何修改示例代码绘制含两组最值的DataFrame棒棒糖图

问题与解决方案

问题描述

现有如下结构的DataFrame:

Country variable      value
0                 Afghanistan     Area  38.232510
1                 Afghanistan     Yield  70.081666
2                   Argentina     Area  96.776730
3                   Argentina     Area  60.047651
4                   Argentina     Yield  66.811117
..                        ...      ...        ...
133  United States Of America    Yield  53.536069
134  United States Of America    Area   76.975885
135  United States Of America    Yield  19.987656
136                    Zambia    Yield  39.493612
137                    Zambia    Yield  35.384809

需要参考双组棒棒糖图的实现逻辑,为每个国家的Area和Yield分组分别绘制最小值和最大值,并用hue区分分组,询问如何修改示例代码。

实现步骤与代码

1. 聚合数据:计算每个国家+分组的极值

首先对原始DataFrame按Country和variable分组,计算每组的min和max值,整理为适合绘图的格式:

import pandas as pd

# 假设原始数据存储在df变量中
agg_df = df.groupby(['Country', 'variable'])['value'].agg(['min', 'max']).reset_index()
# 将min/max转为长格式,方便后续绘图
plot_df = agg_df.melt(id_vars=['Country', 'variable'], var_name='stat', value_name='value')

2. 绘制适配需求的棒棒糖图

参考原示例的matplotlib逻辑,调整为支持hue区分分组、展示极值的版本:

import matplotlib.pyplot as plt
import seaborn as sns

# 设置绘图风格
sns.set_style("whitegrid")

# 创建画布
fig, ax = plt.subplots(figsize=(12, 8))

# 定义分组颜色映射
color_map = {'Area': '#1f77b4', 'Yield': '#ff7f0e'}

# 绘制连接min和max的竖线
for country in plot_df['Country'].unique():
    country_data = plot_df[plot_df['Country'] == country]
    # 处理Area组的竖线
    area_vals = country_data[country_data['variable'] == 'Area']['value'].values
    if len(area_vals) == 2:
        ax.plot([country, country], area_vals, color=color_map['Area'], alpha=0.5)
    # 处理Yield组的竖线
    yield_vals = country_data[country_data['variable'] == 'Yield']['value'].values
    if len(yield_vals) == 2:
        ax.plot([country, country], yield_vals, color=color_map['Yield'], alpha=0.5)

# 绘制极值散点:用hue区分分组,用marker区分min/max
sns.scatterplot(data=plot_df, x='Country', y='value', hue='variable', style='stat', 
                palette=color_map, s=150, ax=ax)

# 调整坐标轴,避免国家名称重叠
plt.xticks(rotation=45, ha='right')

# 添加标题与标签
ax.set_title('Country Area & Yield Min/Max Lollipop Plot', fontsize=14)
ax.set_xlabel('Country', fontsize=12)
ax.set_ylabel('Value', fontsize=12)

# 调整图例位置
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')

plt.tight_layout()
plt.show()

关键说明

  • 数据聚合是核心:原示例的DataFrame直接包含每组的两个值,而你的数据需要先通过groupby计算每个国家+分组的极值,才能匹配绘图逻辑。
  • 绘图分两步:先画连接min和max的竖线,再用散点标记极值点,通过hue区分Area和Yield,style区分最小值/最大值,让信息层级更清晰。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 05:32:45