You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Matplotlib中为DataFrame分组条形图指定自定义性别颜色?

为Pandas分组条形图指定自定义性别颜色

你可以通过在plot.bar()方法中传入color参数实现自定义颜色,核心是确保颜色与性别列的对应关系准确。以下是两种可靠的实现方式:

方式一:按列顺序直接指定颜色

先确认b.unstack()后生成的DataFrame的列顺序(即性别类别顺序),再按顺序传入对应颜色:

import matplotlib.pyplot as plt

# 原有分组逻辑
a = df["Gender"]
b = a.groupby(df["Countries"]).value_counts()

# 可通过print(b.unstack().columns)查看实际列顺序,此处假设为['男性', '女性']
b.unstack().plot.bar(color=['#1f77b4', '#ff80ab'])

plt.xlabel("Countries")
plt.ylabel("Count of People")
plt.title("Count of Genders by Countries")
plt.show()

方式二:用字典映射颜色(更稳妥)

通过字典直接绑定性别与颜色,无需担心列顺序变化的问题:

import matplotlib.pyplot as plt

# 原有分组逻辑
a = df["Gender"]
b = a.groupby(df["Countries"]).value_counts()

# 定义性别-颜色映射字典
gender_color_map = {
    '男性': '#1f77b4',  # 蓝色
    '女性': '#ff80ab'   # 粉色
}

# 根据列名匹配对应颜色
custom_colors = [gender_color_map[col] for col in b.unstack().columns]

b.unstack().plot.bar(color=custom_colors)

plt.xlabel("Countries")
plt.ylabel("Count of People")
plt.title("Count of Genders by Countries")
plt.show()

注意事项

  • 若Gender列是英文(如'Male'/'Female'),只需修改字典中的键名,例如'Male': '#1f77b4', 'Female': '#ff80ab'
  • 颜色值支持十六进制码、颜色名称(如'blue'/'pink')或RGB元组(如(0.125, 0.467, 0.710))

内容的提问来源于stack exchange,提问作者Akshay Lokhande

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 18:51:02