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

如何调整Seaborn coolwarm调色板的颜色占比及排列顺序

调整Seaborn Coolwarm调色板的颜色占比与顺序

要实现80%柱状条为红色、20%为蓝色的效果,或是调整颜色排列顺序,可以通过以下两种方式操作:

方法一:调整颜色渐变区间(推荐)

通过控制数值映射范围,让coolwarm调色板更多偏向红色区域:

import numpy as np
import seaborn
import matplotlib.pyplot as plt

n = df['Col1'].shape[0]
# 生成0.2到1的数值区间,红色系占比80%(1-0.2=0.8)
color_values = np.linspace(0.2, 1, n)
# 将数值映射为coolwarm调色板对应的颜色
custom_palette = seaborn.color_palette("coolwarm", as_cmap=True)(color_values)

# 绘制柱状图
plt.bar(df['Col1'], df['Col2'], width=0.97, color=custom_palette)
plt.show()
  • 若要让蓝色占80%,只需把linspace的范围改为np.linspace(0, 0.8, n)
  • 要调整颜色排列顺序(比如把蓝色柱子放在最后),反转调色板即可:custom_palette[::-1]

方法二:手动截取调色板颜色

直接截取coolwarm调色板的指定部分,组合成自定义配色:

import seaborn
import matplotlib.pyplot as plt

n = df['Col1'].shape[0]
# 获取coolwarm完整调色板(256种颜色)
full_coolwarm = seaborn.color_palette("coolwarm", 256)
# 截取前20%蓝色系和后80%红色系
blue_part = full_coolwarm[:int(256*0.2)]
red_part = full_coolwarm[-int(256*0.8):]
custom_palette = blue_part + red_part

# 采样到对应柱子数量的颜色
final_palette = [custom_palette[int(i * len(custom_palette)/n)] for i in range(n)]

plt.bar(df['Col1'], df['Col2'], width=0.97, color=final_palette)
plt.show()

这种方式更直观,适合需要精确控制颜色区间的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 00:55:00