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

ggplot2斜率图变量着色:基于增长值调整线条颜色

解决方法

步骤1:计算增长幅度并关联到原数据框

先计算每个Domain从中期到末期的均值变化,把增长值合并回原数据框,这样ggplot就能直接调用该字段控制颜色:

library(dplyr)
library(tidyr)
library(forcats)
library(ggplot2)
library(stringr)

# 计算各Domain的增长值:Final均值 - Midblock均值
growth_df <- Domains_Graph %>%
  pivot_wider(names_from = Test, values_from = Means) %>%
  mutate(growth = Final - Midblock) %>%
  select(Domain, growth)

# 将增长值合并到原数据框
Domains_Graph <- Domains_Graph %>%
  left_join(growth_df, by = "Domain")

# 修正Test的因子顺序(注意原数据中是"Midblock",和代码里的"Mid-block"统一)
Domains_Graph$Test <- fct_relevel(factor(Domains_Graph$Test), "Midblock", "Final")

步骤2:两种方式实现Domain A为最深色

方式一:手动指定颜色(精准控制)

直接把最深紫色分配给Domain A,其余Domain使用Purples调色板的剩余颜色:

# 获取Purples调色板颜色,数量匹配Domain总数
domain_count <- n_distinct(Domains_Graph$Domain)
purple_palette <- brewer.pal(n = domain_count, "Purples")

# 构建颜色向量,确保Domain A用最深色
color_vec <- setNames(purple_palette, unique(Domains_Graph$Domain))
color_vec["A"] <- tail(purple_palette, 1)

# 绘图
plot <- ggplot(data = Domains_Graph, aes(x = Test, y = Means, group = Domain, color = Domain)) +
  geom_line(size = 2) +
  geom_point(size = 3) +
  scale_color_manual(values = color_vec) +
  ggtitle(str_wrap("中期到期末各领域均值变化", width = 40)) +
  theme(plot.title = element_text(hjust = 0.5)) +
  theme(axis.text.x = element_text(hjust = c(1, 0))) +
  theme_minimal()

print(plot)

方式二:基于增长值映射颜色(增长越大颜色越深)

让颜色深浅直接对应增长幅度,Domain A因增长最大自然显示最深色:

plot <- ggplot(data = Domains_Graph, aes(x = Test, y = Means, group = Domain, color = growth)) +
  geom_line(size = 2) +
  geom_point(size = 3) +
  scale_color_gradient(low = "lavender", high = "darkorchid4") +
  labs(color = "增长幅度") +
  ggtitle(str_wrap("中期到期末各领域均值变化", width = 40)) +
  theme(plot.title = element_text(hjust = 0.5)) +
  theme(axis.text.x = element_text(hjust = c(1, 0))) +
  theme_minimal()

print(plot)

注意事项

  • 原代码中fct_relevel的参数"Mid-block"和数据中的"Midblock"不匹配,需统一修正,否则因子顺序设置无效。
  • 若Domain数量超过15,Purples调色板默认最多支持11种颜色,建议改用scale_color_viridis_c或自定义渐变配色。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 01:43:33