Python新手求助:基于Pivot Table结果绘制分组柱状图
Hey there! I see you've already nailed the pivot table setup and no-show proportion calculations—great work! Let's get that grouped bar chart sorted out, where each health category has separate colored bars for male and female.
Using Seaborn (Recommended for Newbies)
Seaborn makes this kind of grouped chart super straightforward with its barplot function, which handles gender-based grouping automatically via the hue parameter. Here's how to implement it:
First, make sure you have the required libraries imported (if you haven't already):
import seaborn as sns import matplotlib.pyplot as plt
Then run this code to generate your chart:
# Set a clean, readable plot style (optional but improves aesthetics) sns.set_style("whitegrid") # Create the grouped bar chart plt.figure(figsize=(10, 6)) # Adjust plot size to your preference ax = sns.barplot( x='category', y='no_show_prop', hue='gender', data=data_pv, palette='Set2' # Pick a color palette you like ) # Add clear labels and a title ax.set_title('No-Show Proportion by Health Category and Gender', fontsize=14) ax.set_xlabel('Health Condition Category', fontsize=12) ax.set_ylabel('No-Show Proportion (%)', fontsize=12) # Adjust legend position to avoid overlapping bars plt.legend(title='Gender', bbox_to_anchor=(1.05, 1), loc='upper left') # Ensure labels don't get cut off plt.tight_layout() # Display the plot plt.show()
This will give you exactly what you want: each category on the X-axis, with two distinct bars (one for F, one for M) showing the no-show percentage. The hue parameter is the key here—it tells Seaborn to split bars by the gender column automatically.
If You Prefer Matplotlib (For More Low-Level Control)
If you want to understand the underlying mechanics, you can build the chart manually with Matplotlib:
import matplotlib.pyplot as plt import numpy as np # Get unique categories and genders from your data categories = data_pv['category'].unique() genders = data_pv['gender'].unique() x = np.arange(len(categories)) # Base X positions for categories bar_width = 0.35 # Width of each individual bar # Initialize the plot fig, ax = plt.subplots(figsize=(10, 6)) # Loop through genders to plot their bars for idx, gender in enumerate(genders): # Filter data for the current gender gender_subset = data_pv[data_pv['gender'] == gender] # Plot bars with an offset to avoid overlapping ax.bar(x + idx*bar_width, gender_subset['no_show_prop'], bar_width, label=gender) # Customize the plot ax.set_title('No-Show Proportion by Health Category and Gender', fontsize=14) ax.set_xlabel('Health Condition Category', fontsize=12) ax.set_ylabel('No-Show Proportion (%)', fontsize=12) # Set X-ticks to sit between grouped bars ax.set_xticks(x + bar_width/2) ax.set_xticklabels(categories) ax.legend(title='Gender') plt.tight_layout() plt.show()
Why Your Groupby Attempt Might Have Failed
Chances are your groupby approach didn't work because you were trying to plot directly from the grouped object without reshaping it into a format that's easy to plot. The Seaborn method avoids this headache entirely, as it works seamlessly with your existing data_pv DataFrame (which is already in the perfect "long format" for grouped plots).
Give either method a try—they should get you the chart you're aiming for!
内容的提问来源于stack exchange,提问作者LOR121

