如何使用Seaborn基于给定的SR DataFrame制作类似Excel生成的柱状图?
Hey there! To recreate that Excel-style grouped bar chart using your SR DataFrame with Seaborn, we’ll need to reshape the data first (Seaborn works best with long-format data for grouped plots) and then use barplot to get those side-by-side bars for each performance metric. Here's a complete, step-by-step solution:
Step 1: Import Required Libraries
First, let's load the tools we need:
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt
Step 2: Define Your DataFrame
Confirm your SR DataFrame is set up correctly (you can reuse your existing code here):
SR = pd.DataFrame( [ ['Linear Regression', 0.9533333333333334, 0.9747081712062257, 0.8255813953488372], ['Ridge Classifier', 0.905, 0.9980544747081712, 0.3488372093023256], ['Decision Tree Classifier',0.9883333333333333,0.9922178988326849,0.9651162790697675], ['Random Forest', 0.9916666666666667, 0.9980544747081712, 0.9534883720930233], ['XG Boost', 0.9916666666666667, 0.9980544747081712, 0.9534883720930233], ['Neural Network', 1.0, 1.0, 1.0] ], columns = ['Model', 'Accuracy','Sensitivity','Specificity'] )
Step 3: Reshape Data to Long Format
Seaborn’s grouped bar plots rely on long-format data (each row represents one model-metric-score combination). We’ll use pd.melt() to convert your wide DataFrame:
# Convert wide-format data to long-format sr_long = pd.melt( SR, id_vars='Model', # Keep Model as the identifier column value_vars=['Accuracy', 'Sensitivity', 'Specificity'], # Metrics to unpivot var_name='Metric', # Name for the new metric column value_name='Score' # Name for the new score column )
Step 4: Plot the Grouped Bar Chart
Now we’ll create the chart with customizations to match Excel’s style—including value labels on bars, rotated x-axis labels, and a clean layout:
# Set a clean plot style sns.set_style("whitegrid") # Create a figure with a reasonable size plt.figure(figsize=(12, 6)) # Generate the grouped bar plot ax = sns.barplot( x='Model', y='Score', hue='Metric', data=sr_long, palette='viridis' # You can swap this for other palettes like 'Blues' or 'Set2' ) # Add plot title and axis labels ax.set_title('Model Performance Metrics', fontsize=14, pad=20) ax.set_xlabel('Model', fontsize=12) ax.set_ylabel('Score (0-1)', fontsize=12) # Extend y-axis slightly to fit value labels ax.set_ylim(0, 1.1) # Rotate x-axis labels to avoid overlap (common with long model names) plt.xticks(rotation=45, ha='right') # Add value labels on top of each bar (just like Excel does) for p in ax.patches: height = p.get_height() ax.text( p.get_x() + p.get_width()/2., height, f'{height:.3f}', # Format scores to 3 decimal places ha='center', va='bottom', fontsize=10 ) # Move legend outside the plot for better readability plt.legend(title='Performance Metric', bbox_to_anchor=(1.05, 1), loc='upper left') # Remove unnecessary spines for a cleaner look sns.despine() # Adjust layout to prevent label cutoff plt.tight_layout() # Display the plot plt.show()
What This Does
This code will produce a grouped bar chart where each model has three side-by-side bars for Accuracy, Sensitivity, and Specificity—mirroring the Excel chart you referenced. The key tweaks (like value labels and rotated ticks) make the plot just as readable as its Excel counterpart.
内容的提问来源于stack exchange,提问作者Chan Wee How

