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

如何让ggplot2图例文字颜色与填充色一致并实现文本换行

问题

我尝试让ggplot2图例文字颜色与填充色保持一致,参考相关内容后仍未完全解决。我的图例文字较长,希望实现文本换行,尝试用\n但无效,且不希望图例文字分成三行,要使其大致对应所在图例段的下方。

示例图

数据生成代码

test <- data.frame(Episode_Time=c(1:13),
               Stress=c(71.02, 71.66, 74.70, 74.22, 
                        71.70, 75.96, 76.85, 69.81, 
                        71.70, 73.83, 75.25, 72.56, 
                        63.35),
               Post=c(0,0,0,0,0,0,1,2,2,2,2,2,2))

test$Post_f <- factor(test$Post, levels=c(0,1,2), labels=c("Pre","ER","Post"))

当前绘图代码

cols <- c("#687EF1","#59CBCA","#FCD145")
ggplot(test, aes(x = Episode_Time, y = Stress)) +
  geom_rect(aes(xmin=Episode_Time-.5,xmax=Episode_Time+.5,ymin=50,ymax=82,fill=Post_f),alpha=0.5) +
  stat_smooth(method="loess", se=FALSE, linewidth=3, color="black") +
  # scale_x_continuous(breaks=c(2,7,11.5), labels=c("Stress
30 Minutes
Pre-Activity",
  #                                                 "Emotion
Regulation
Skill Activity",
  #                                                 "Stress
30 Minutes
Post-Activity")) +
  scale_fill_manual(values=cols,
                    labels=paste("<span style='color:",
                                 cols,
                                 "'>",
                                 c("Stress
30 Minutes
Pre-Activity",
                                   "Emotion
Regulation
Skill Activity",
                                   "Stress
30 Minutes
Post-Activity"),
                                  "</span>")) +
  ylab("Physiological Stress") +
  theme_minimal() +
    theme(
    axis.text=element_blank(),
    axis.title.x=element_blank(),
    axis.title.y=element_text(size=25,color="black"),
    legend.position="right",
    legend.title=element_blank(),
    legend.text=element_markdown(size=20),
    axis.line.y = element_line(arrow = grid::arrow(length = unit(0.4, "cm"), 
                                                     ends = "both",  # last is to just have up arrow 
                                                     type = "closed"),linewidth=1)
  )
解决方案

1. 核心问题解决思路

  • 利用element_markdown()支持HTML标签的特性,用<br>替代\n实现精准换行
  • 调整图例文本对齐方式与方块高度,让文字对应在图例方块下方
  • 直接定义带颜色样式的标签,避免拼接字符串可能出现的格式问题

修改后的完整代码

cols <- c("#687EF1","#59CBCA","#FCD145")
# 自定义图例标签,用<br>控制换行位置,同时匹配填充色
legend_labels <- c(
  "<span style='color:#687EF1'>Stress<br>30 Minutes Pre-Activity</span>",
  "<span style='color:#59CBCA'>Emotion Regulation<br>Skill Activity</span>",
  "<span style='color:#FCD145'>Stress<br>30 Minutes Post-Activity</span>"
)

ggplot(test, aes(x = Episode_Time, y = Stress)) +
  geom_rect(aes(xmin=Episode_Time-.5,xmax=Episode_Time+.5,ymin=50,ymax=82,fill=Post_f),alpha=0.5) +
  stat_smooth(method="loess", se=FALSE, linewidth=3, color="black") +
  scale_fill_manual(values=cols, labels=legend_labels) +
  ylab("Physiological Stress") +
  theme_minimal() +
  theme(
    axis.text=element_blank(),
    axis.title.x=element_blank(),
    axis.title.y=element_text(size=25,color="black"),
    legend.position="right",
    legend.title=element_blank(),
    # 左对齐文本,让文字对应图例方块下方
    legend.text=element_markdown(size=20, hjust=0),
    # 调整图例方块高度,优化文字与方块的对应关系
    legend.key.height=unit(1.5, "line"),
    axis.line.y = element_line(arrow = grid::arrow(length = unit(0.4, "cm"), 
                                                   ends = "both", 
                                                   type = "closed"),linewidth=1)
  )

关键修改说明

  • 用HTML<br>标签实现精准换行,解决\n无效的问题,同时按需求控制换行次数
  • 给每个图例标签单独设置对应填充色的文字颜色,确保颜色匹配
  • 通过hjust=0设置文本左对齐,配合legend.key.height调整方块高度,让文字对齐到图例方块下方
  • 直接编写完整标签字符串,避免paste()拼接可能产生的格式错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 16:57:33