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

如何让hvplot箱线图使用默认颜色循环匹配其他图表颜色?

问题描述

我有一个简单的hvplot示例,需要将折线图(line plot)、直方图(histogram)和箱线图(box plot)三个图表并排展示。请问是否有简便方法,让每个箱线图使用默认颜色循环(default colour cycle)中的颜色,与另外两个图表的颜色相匹配?

当前代码如下:

import pandas as pd
import hvplot.pandas

data = pd.read_csv('https://raw.githubusercontent.com/ChrisWalshaw/DataViz/master/Data/Products/DailySales.csv', index_col=0)
data.index = pd.to_datetime(data.index)
print(data.head())

selected = ['A', 'F', 'L']

plot1 = data[selected].hvplot.line(
    frame_height=300, frame_width=300,
)
plot2 = data[selected].hvplot.hist(
    frame_height=300, frame_width=300,
)
plot3 = data[selected].hvplot.box(
    frame_height=300, frame_width=300,
)
plot = plot1 + plot2 + plot3
hvplot.show(plot)

当前输出为并排的折线图、直方图和箱线图,如图所示:
output - line plot, histogram, box plots


解决方案

要让箱线图的颜色与折线图、直方图的默认颜色循环匹配,只需给箱线图的color参数指定默认颜色循环即可,有两种简洁实现方式:

方式1:提取默认颜色列表指定

先获取hvplot的默认颜色循环列表,再传给箱线图的color参数:

import pandas as pd
import hvplot.pandas
from hvplot.plotting.util import get_cmap_list

data = pd.read_csv('https://raw.githubusercontent.com/ChrisWalshaw/DataViz/master/Data/Products/DailySales.csv', index_col=0)
data.index = pd.to_datetime(data.index)

selected = ['A', 'F', 'L']
# 获取默认颜色循环,截取与选中列数量匹配的颜色
default_colors = get_cmap_list('default')[:len(selected)]

plot1 = data[selected].hvplot.line(
    frame_height=300, frame_width=300,
)
plot2 = data[selected].hvplot.hist(
    frame_height=300, frame_width=300,
)
plot3 = data[selected].hvplot.box(
    frame_height=300, frame_width=300,
    color=default_colors  # 绑定默认颜色
)
plot = plot1 + plot2 + plot3
hvplot.show(plot)

方式2:直接指定颜色循环字符串

无需手动提取颜色列表,直接用cycle(default)指定颜色循环:

# 仅修改箱线图部分,其余代码不变
plot3 = data[selected].hvplot.box(
    frame_height=300, frame_width=300,
    color='cycle(default)'
)

原理说明

  • 折线图和直方图绘制多列数据时,会自动依次使用默认颜色循环中的颜色;
  • 箱线图默认所有箱线共用同一种颜色,通过显式指定color为默认颜色循环,可让每个箱线对应折线/直方图中对应列的颜色,实现视觉统一。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 00:53:21