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

Python中如何制作自定义颜色的分组水平条形图及多子图

Python水平条形图:多子图布局与自定义颜色设置

问题说明

我需要在Python中制作包含3个子图的水平条形图,每个子图包含5组、每组4个条形,同时修改条形的默认颜色。基于以下参考代码,请问:
a)如何将每组条形的颜色改为深蓝、浅蓝、深紫、浅紫;
b)如何结合代码fig, (ax1, ax2, ax3) = plt.subplots(1, 3)实现多子图布局?

参考代码:

speed = [40, 48, 52, 69, 88]
lifespan = [70, 1.5, 25, 12, 28]
height = [35, 5, 18, 17, 43]
width = [40, 18, 35, 37, 15]
index = ['elephant', 'rabbit', 'giraffe', 'coyote', 'horse']
df = pd.DataFrame({'speed': speed, 'lifespan': lifespan, 'height': height, 'width': width}, index=index)
ax = df.plot.barh()

解决方案

a)自定义条形颜色

直接通过plot.barh()的color参数传入一组颜色值即可,颜色对应DataFrame中每一列的条形。你需要的配色可以用十六进制颜色码定义:

  • 深蓝:#003366
  • 浅蓝:#6699CC
  • 深紫:#330066
  • 浅紫:#9966CC

示例代码片段:

color_list = ['#003366', '#6699CC', '#330066', '#9966CC']
ax = df.plot.barh(color=color_list)

b)多子图布局实现

用plt.subplots(1, 3)创建1行3列的子图框架后,只需要在df.plot.barh()中通过ax参数指定每个子图对应的坐标轴对象,就能把条形图绑定到对应子图上。

完整可运行代码

import pandas as pd
import matplotlib.pyplot as plt

# 准备数据
speed = [40, 48, 52, 69, 88]
lifespan = [70, 1.5, 25, 12, 28]
height = [35, 5, 18, 17, 43]
width = [40, 18, 35, 37, 15]
index = ['elephant', 'rabbit', 'giraffe', 'coyote', 'horse']
df = pd.DataFrame({'speed': speed, 'lifespan': lifespan, 'height': height, 'width': width}, index=index)

# 自定义配色
color_list = ['#003366', '#6699CC', '#330066', '#9966CC']

# 创建1行3列的子图布局,设置合适画布尺寸
fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(15, 6))

# 在每个子图绘制水平条形图
df.plot.barh(ax=ax1, color=color_list, title='子图1')
df.plot.barh(ax=ax2, color=color_list, title='子图2')
df.plot.barh(ax=ax3, color=color_list, title='子图3')

# 自动调整布局,避免元素重叠
plt.tight_layout()
plt.show()

补充提示

  • 如果每个子图需要展示不同的数据子集,可修改传入绘图函数的DataFrame片段,比如df[['speed', 'height']].plot.barh(ax=ax1, ...)
  • tight_layout()函数能自动优化子图间距,防止标题、坐标轴标签等内容互相遮挡

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 14:25:20