如何基于DataFrame分组数据绘制带极值误差棒的统计图
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 theaggfunction with'median','mode', or any other statistic you need for the Y-axis. - Error Bar Customization: Adjust
capsizeto make the error bar ends wider/narrower, and changecolor/ecolorto match your preferred style. - Replace Sample Data: Swap out the sample
dfwith 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

