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

如何修改R语言中Treemap(树形图)的配色方案?

如何修改Treemap(树形图)的配色方案?

我用treemapify和ggplot2绘制了树形图,想要更新当前的配色方案,请问该怎么操作?

原始代码如下:

group <- c("China", "India", "United States", "Germany", "Russia",
        "Japan", "South Africa", "South Korea", "Poland", "Australia")
value <- c(4320, 966, 731, 257, 230,
       210, 202, 157, 149, 130)

df <- data.frame(group, value) 
# install.packages("treemapify")
library(treemapify)
# install.packages("ggplot2")
library(ggplot2)

ggplot(df, aes(area = value, fill = group,
           label = paste(group, value, sep = "\n"))) +
geom_treemap() +
geom_treemap_text(colour = "white",
                place = "centre",
                size = 15) + 
theme(legend.position = "none" )

解决方案:三种修改配色的方法

1. 使用ggplot2内置离散调色板

ggplot2提供了多种开箱即用的离散配色方案,适配分类变量(这里的group):

示例:ColorBrewer调色板

ggplot(df, aes(area = value, fill = group,
           label = paste(group, value, sep = "\n"))) +
geom_treemap() +
geom_treemap_text(colour = "white", place = "centre", size = 15) +
scale_fill_brewer(palette = "Set3")  # 可替换为"Paired""Dark2"等其他调色板
theme(legend.position = "none")

示例:色盲友好的viridis调色板

ggplot(df, aes(area = value, fill = group,
           label = paste(group, value, sep = "\n"))) +
geom_treemap() +
geom_treemap_text(colour = "white", place = "centre", size = 15) +
scale_fill_viridis_d(option = "plasma")  # option可选"viridis""magma"等
theme(legend.position = "none")

2. 完全自定义分组颜色

如果需要指定每个分组的具体颜色,使用scale_fill_manual传入颜色向量(颜色数量需与分组数一致):

# 自定义10个分组对应的颜色
custom_colors <- c("#FF6B6B", "#4ECDC4", "#45B7D1", "#96CEB4", "#FFEAA7",
                   "#DDA0DD", "#98D8C8", "#F7DC6F", "#BB8FCE", "#85C1E9")

ggplot(df, aes(area = value, fill = group,
           label = paste(group, value, sep = "\n"))) +
geom_treemap() +
geom_treemap_text(colour = "white", place = "centre", size = 15) +
scale_fill_manual(values = custom_colors) +
theme(legend.position = "none")

3. 基于数值渐变配色(可选)

如果想让颜色随value数值大小变化,将fill映射到value并使用连续调色板:

ggplot(df, aes(area = value, fill = value,
           label = paste(group, value, sep = "\n"))) +
geom_treemap() +
geom_treemap_text(colour = "white", place = "centre", size = 15) +
scale_fill_gradient(low = "#F0F8FF", high = "#2E8B57")  # 浅到深的绿色渐变
# 也可用viridis连续调色板:scale_fill_viridis_c(option = "cividis")
theme(legend.position = "right")  # 显示数值对应颜色的图例

内容的提问来源于stack exchange,提问作者Data and AI Nerd

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 22:57:08