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

Python绘制按国家统计客户数堆叠面积图及配色、Bokeh实现咨询

1. Pandas原生绘图自定义配色方案

你可以给plot方法传入color参数自定义配色,参数支持两种传入格式:

  • 传入颜色列表,列表顺序和你unstack之后的国家列顺序一一对应即可
  • 传入字典,直接给指定国家绑定固定配色,无需对应顺序

示例代码如下:

# 方式1:传入颜色列表
custom_colors = ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd"]
table.groupby(['date','country'])['people'].sum().unstack().plot(
    kind='area',
    figsize=(10,4),
    color=custom_colors
)

# 方式2:传入配色映射字典
color_map = {
    "USA": "#1f77b4",
    "France": "#ff7f0e", 
    "Germany": "#2ca02c",
    "Poland": "#d62728",
    "China": "#9467bd"
}
table.groupby(['date','country'])['people'].sum().unstack().plot(
    kind='area',
    figsize=(10,4),
    color=color_map
)
2. Bokeh实现堆叠面积图代码示例

Bokeh绘制的可视化支持交互效果,比如鼠标悬浮查看数值、缩放平移等,完整可运行代码如下:

import pandas as pd
from bokeh.models import ColumnDataSource, HoverTool
from bokeh.plotting import figure, show
from bokeh.palettes import Category10 # 预设配色库,也可以自定义颜色列表

# 第一步:处理数据为Bokeh需要的格式
df = table.groupby(['date','country'])['people'].sum().unstack().reset_index()
df['date'] = pd.to_datetime(df['date']) # 转换为时间格式适配时间轴
countries = df.columns.drop('date').tolist() # 提取国家列表
colors = Category10[len(countries)] # 自动匹配对应数量的预设配色,也可替换为自定义颜色列表
source = ColumnDataSource(df) # 构建Bokeh专用数据源

# 第二步:创建画布并绘图
p = figure(
    x_axis_type='datetime', 
    width=1000, 
    height=400, 
    title='各国客户数量堆叠面积图',
    x_axis_label='日期', 
    y_axis_label='客户数量'
)
# 绘制堆叠面积图
p.varea_stack(
    stackers=countries, 
    x='date', 
    color=colors, 
    source=source, 
    legend_label=countries
)

# 第三步:配置交互效果和样式
p.legend.location = 'top_left'
# 配置鼠标悬浮提示,放上去就能看到对应国家的人数
hover = HoverTool(
    tooltips=[
        ('日期', '@date{%F}'),
        ('国家', '$name'),
        ('客户数量', '@$name')
    ], 
    formatters={'@date': 'datetime'}
)
p.add_tools(hover)

# 展示图表
show(p)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 17:06:04