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

如何为特定箱线图设置颜色(ACT为红色、NSW为黑色)

问题:如何为箱线图指定ACT/NSW数据的颜色?

现有如下Python绘制箱线图的代码,需要将所有ACT数据对应的箱线图设置为红色,NSW数据对应的设置为黑色:

df2020 = transport_data.loc['2020']
df2021 = transport_data.loc['2021']
df2022 = transport_data.loc['2022']

fig = plt.subplots(figsize = (20,7))
ax = [
    plt.subplot(131),
    plt.subplot(132),
    plt.subplot(133) ]

df2020.boxplot(grid=False, rot=90, fontsize=10, ax = ax[0])
df2021.boxplot(grid=False, rot=90, fontsize=10, ax = ax[1])
df2022.boxplot(grid=False, rot=90, fontsize=10, ax = ax[2])


ax[0].set_xlabel('Types of Passengers', fontsize = '12')
ax[1].set_xlabel('Types of Passengers', fontsize = '12')
ax[2].set_xlabel('Types of Passengers', fontsize = '12')
ax[0].set_ylabel('Number of Pssengers', fontsize = '12')
ax[1].set_ylabel('Number of Passengers', fontsize = '12')
ax[2].set_ylabel('Number of Passengers', fontsize = '12')
ax[0].set_title('2020', fontsize = '15')
ax[1].set_title('2021', fontsize = '15')
ax[2].set_title('2022', fontsize = '15')

解决方案

要实现指定数据的颜色,需要启用箱线图的填充样式,再根据x轴标签匹配颜色,具体修改如下:

  1. 调用boxplot()时添加patch_artist=True参数,允许修改箱体的填充颜色;
  2. 定义颜色映射规则,遍历每个子图的箱线图元素,根据标签设置对应颜色。

修改后的完整代码:

import matplotlib.pyplot as plt
import pandas as pd

df2020 = transport_data.loc['2020']
df2021 = transport_data.loc['2021']
df2022 = transport_data.loc['2022']

fig, _ = plt.subplots(figsize=(20,7))
ax = [
    plt.subplot(131),
    plt.subplot(132),
    plt.subplot(133)
]

# 定义颜色映射
color_map = {'ACT': 'red', 'NSW': 'black'}

# 绘制箱线图并设置颜色
for year_df, axis in zip([df2020, df2021, df2022], ax):
    # 启用patch_artist才能修改填充色
    bp = year_df.boxplot(grid=False, rot=90, fontsize=10, ax=axis, patch_artist=True)
    # 获取x轴标签
    labels = [tick.get_text() for tick in axis.get_xticklabels()]
    # 遍历每个箱体,设置对应颜色
    for box, label in zip(bp['boxes'], labels):
        if label in color_map:
            box.set_facecolor(color_map[label])

# 统一设置轴标签和标题
for axis, title in zip(ax, ['2020', '2021', '2022']):
    axis.set_xlabel('Types of Passengers', fontsize='12')
    axis.set_ylabel('Number of Passengers', fontsize='12')
    axis.set_title(title, fontsize='15')

plt.tight_layout()
plt.show()

关键说明:

  • patch_artist=True:开启这个参数后,箱线图的箱体才支持自定义填充颜色;
  • 遍历bp['boxes']:每个box对应一个数据列的箱体,和x轴标签一一对应;
  • 通过color_map匹配标签和颜色,确保ACT显示红色、NSW显示黑色,其他数据列保持默认样式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 00:25:18