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

如何基于DataFrame分组数据绘制带极值误差棒的统计图

Plot Grouped Data with Min-Max Error Bars

Hey there! Let's walk through how to create the plot you're looking for—grouped by Group on the X-axis, with B values (using a central tendency like mean) on the Y-axis, and error bars spanning each group's minimum and maximum B values.

First, we'll need to aggregate your DataFrame to get the necessary stats per group, then plot using either Matplotlib or Seaborn. Here's a step-by-step solution:

Step 1: Prepare the Data

First, we'll group your data by Group and calculate the mean (as the central point), minimum, and maximum of column B. We'll also sort the groups in descending order as you specified.

import pandas as pd
import matplotlib.pyplot as plt

# Replace this with your actual DataFrame
df = pd.DataFrame({
    'Group': [5,5,5,2,2,2,2,2,2,2,3,3],
    'B': [10,12,15,8,9,11,13,14,16,17,5,7]
})

# Aggregate stats per Group: mean, min, max of B
grouped_data = df.groupby('Group')['B'].agg(['mean', 'min', 'max']).reset_index()

# Sort groups in descending order
grouped_data = grouped_data.sort_values('Group', ascending=False)

Step 2: Plot with Matplotlib (Line Plot)

This creates a line plot with circles at each group's mean, and error bars from min to max:

plt.figure(figsize=(8, 6))

# Define X, Y, and error values
x = grouped_data['Group']
y = grouped_data['mean']
# Calculate lower (mean - min) and upper (max - mean) error bounds
error_bounds = [y - grouped_data['min'], grouped_data['max'] - y]

# Plot with error bars
plt.errorbar(x, y, yerr=error_bounds, fmt='o-', capsize=5, color='navy', ecolor='crimson')

# Add labels and title
plt.xlabel('Group', fontsize=12)
plt.ylabel('Value of B', fontsize=12)
plt.title('Grouped B Values (Mean) with Min-Max Error Bars', fontsize=14)

plt.tight_layout()
plt.show()

Step 3: Alternative: Bar Plot with Seaborn

If you prefer a bar plot instead, here's how to do it with Seaborn:

import seaborn as sns

plt.figure(figsize=(8, 6))

# Create bar plot with custom error bars
sns.barplot(
    x='Group', 
    y='mean', 
    data=grouped_data,
    yerr=error_bounds,
    capsize=5,
    color='skyblue'
)

plt.xlabel('Group', fontsize=12)
plt.ylabel('Mean of B', fontsize=12)
plt.title('Bar Plot of Mean B with Min-Max Error Bars', fontsize=14)

plt.tight_layout()
plt.show()

Key Notes

  • Customize the Central Value: If you don't want to use the mean, replace 'mean' in the agg function with 'median', 'mode', or any other statistic you need for the Y-axis.
  • Error Bar Customization: Adjust capsize to make the error bar ends wider/narrower, and change color/ecolor to match your preferred style.
  • Replace Sample Data: Swap out the sample df with your actual DataFrame—this code works regardless of how many times each group appears (as long as each group has at least one entry).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 04:20:35