Matplotlib子图颜色交替问题:如何统一所有子图配色?
Hey there! Let's get those subplot colors aligned properly. The issue you're seeing—where the second subplot's colors are flipped relative to the first and third in every column—almost always boils down to category order inconsistency across your year datasets. Here's how to fix it, with two straightforward approaches:
1. Standardize Category Order (Quickest Fix)
The root cause is likely that your 2016 dataset has reversed category order for columns like Sex or Education Level compared to 2015/2017. Matplotlib assigns colors based on the order it encounters categories, so flipping the order flips the colors.
To fix this, we'll force all subplots to use the same category order (pulled from your 2015 data as the reference):
import matplotlib.pyplot as plt hrlist = [hrdata2015, hrdata2016, hrdata2017] titles = ["2015", "2016", "2017"] columns = ["Sex","Education Level","Salary Plan","Grade", "Contract Type","Citizenship", "Division"] for col in columns: # Grab the category order from the 2015 dataset to use as a standard standard_order = hrlist[0][col].value_counts().index plt.figure(figsize=(18, 5)) # Adjust size as needed for idx, (data, title) in enumerate(zip(hrlist, titles)): plt.subplot(1, 3, idx + 1) # Reindex the data to match our standard category order data[col].value_counts().reindex(standard_order).plot(kind='bar') # Swap 'bar' for your plot type plt.title(title) plt.xticks(rotation=45) # Optional: Rotate labels for readability plt.tight_layout() plt.show()
This ensures every subplot for a given column uses the exact same category order, so colors map consistently across all years.
2. Assign Fixed Colors to Categories (More Control)
If you want full control over which color maps to which category (great for brand consistency or accessibility), define a color dictionary that binds specific colors to each category:
import matplotlib.pyplot as plt # Define color mappings for each column's categories category_colors = { "Sex": {"Male": "#1f77b4", "Female": "#ff7f0e"}, "Education Level": {"High School": "#2ca02c", "Bachelor": "#d62728", "Master": "#9467bd", "PhD": "#8c564b"}, "Contract Type": {"Full-time": "#e377c2", "Part-time": "#7f7f7f", "Temporary": "#bcbd22"}, # Add mappings for your other columns here } hrlist = [hrdata2015, hrdata2016, hrdata2017] titles = ["2015", "2016", "2017"] columns = ["Sex","Education Level","Salary Plan","Grade", "Contract Type","Citizenship", "Division"] for col in columns: plt.figure(figsize=(18, 5)) color_map = category_colors.get(col, {}) # Get colors for the current column for idx, (data, title) in enumerate(zip(hrlist, titles)): plt.subplot(1, 3, idx + 1) plot_data = data[col].value_counts() # Match colors to each category in the plot data colors = [color_map[cat] for cat in plot_data.index] plot_data.plot(kind='bar', color=colors) plt.title(title) plt.xticks(rotation=45) plt.tight_layout() plt.show()
This method guarantees that no matter the category order in your datasets, each category will always get its assigned color.
If You're Using Seaborn
If you're using seaborn.countplot instead of pandas plotting, use the order parameter to enforce consistent category order:
import seaborn as sns for col in columns: standard_order = hrlist[0][col].value_counts().index plt.figure(figsize=(18, 5)) for idx, (data, title) in enumerate(zip(hrlist, titles)): plt.subplot(1, 3, idx + 1) sns.countplot(data=data, x=col, order=standard_order) plt.title(title) plt.xticks(rotation=45) plt.tight_layout() plt.show()
Either of these approaches will eliminate the flipped color issue and keep all your subplots visually consistent!
内容的提问来源于stack exchange,提问作者MrSoLoDoLo

