如何让Matplotlib多图表中同一类别保持相同颜色?
解决同一类别在多图表中颜色统一的问题
核心思路是给每个类别绑定固定颜色,通过字典建立「类别-颜色」的映射关系,然后在每个图表中根据当前显示的类别顺序,从字典中提取对应颜色,彻底解决因类别排序不同导致的颜色错位问题。
具体步骤:
- 构建类别-颜色映射字典
先提取数据中所有唯一的Stadtteil类别,将其与你定义的颜色列表my_c一一绑定,确保每个类别对应唯一颜色。 - 为每个图表匹配对应颜色
对每个图表,先获取当前图表显示的类别顺序,再从映射字典中提取每个类别对应的颜色,传递给绘图函数的对应参数(注意:pandas绘图中柱状图用color参数,饼图用colors参数,参数名有区别)。
修改后的完整代码
import pandas as pd import matplotlib.pyplot as plt # 你的颜色列表 my_c = ['green','blue','red','yellow','black'] # 构建类别-颜色映射字典 unique_districts = df['Stadtteil'].unique() color_map = dict(zip(unique_districts, my_c)) fig, ax = plt.subplots(nrows=2, ncols=2) # 第一个柱状图:区域数量统计 counts = df['Stadtteil'].value_counts() bar_colors = [color_map[district] for district in counts.index] counts.plot(kind='bar', ax=ax[0][0], color=bar_colors) ax[0][0].set(xlabel='Stadtteil', ylabel='Anzahl', title='Anzahl Bezirke pro Stadtteil') ax[0][0].xaxis.set_tick_params(labelrotation=45) # 饼图:区域人口总和占比 cross_tab = pd.crosstab( index=df['Stadtteil'], columns='Einwohner', values=df['Einwohner'], aggfunc='sum' ) pie_colors = [color_map[district] for district in cross_tab.index] cross_tab.plot(ax=ax[0][1], kind='pie', legend=False, y='Einwohner', colors=pie_colors) ax[0][1].set(ylabel='') # 第二个柱状图:区域人口总和排序 sum_einwohner = df.groupby('Stadtteil')['Einwohner'].sum().sort_values(ascending=False) bar_colors2 = [color_map[district] for district in sum_einwohner.index] sum_einwohner.plot(kind='bar', ax=ax[1][1], color=bar_colors2) ax[1][1].set(xlabel='Stadtteil', ylabel='Anzahl Einwohner', title='Anzahl Einwohner pro Stadtteil') ax[1][1].xaxis.set_tick_params(labelrotation=45) fig.tight_layout() plt.show()
关键说明:
- 注意pandas绘图参数差异:柱状图用
color,饼图用colors,之前代码中柱状图误用colors可能导致颜色未生效; - 映射字典确保每个类别(如Bronx、Queens)永远对应同一个颜色,不受图表中类别排序的影响;
- 若后续新增类别,只需在
my_c中添加对应颜色,字典会自动匹配(需保证颜色列表长度和类别数量一致)。
内容的提问来源于stack exchange,提问作者user23365924
相关产品推荐
相关产品推荐

