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

R语言ggplot2使用facet_wrap分面时如何独立设置各分面文本颜色

解决方案

核心原理:原有代码仅将treatment作为颜色映射变量,相同treatment在所有分面会复用同一个颜色值。要实现分面独立配色,需要构造「分面标识+处理名」的唯一变量作为颜色映射的依据,给每个组合单独分配颜色。

完整可运行代码

# 示例原始数据
Genotype<- rep(c("CV1","CV2"),each=3)
treatment<-rep(c("T1","T2","T3"),2)
RATIO<- c(0.8,0.7,0.9,1.1,1.0,0.8)
DataA<- data.frame(Genotype,treatment,RATIO)

# 标签数据合并处理
A_labels <- data.frame(Genotype=c("CV1", "CV1", "CV1"),
                       perc= c("NA", "NA","PASS"), treatment=c("T1", "T2", "T3"),
                       RATIO=c(1.0, 0.90, 1.0))
B_labels <- data.frame(Genotype=c("CV2", "CV2", "CV2"),
                       perc= c("TEST", "PASS","FAIL"), treatment=c("T1", "T2", "T3"),
                       RATIO=c(1.2, 1.1, 1.1))
# 合并标签数据,生成唯一颜色映射键
all_labels <- rbind(A_labels, B_labels)
all_labels$color_key <- paste(all_labels$Genotype, all_labels$treatment, sep = "_")

# 绘图代码
library(ggplot2)
ggplot(data=DataA, aes(x=treatment, y=RATIO, fill=treatment)) +
  geom_bar(stat="identity",position="dodge", width = 0.7) + 
  scale_fill_manual(values= c ("Dark gray","Dark blue", "Dark red")) +
  scale_y_continuous(breaks = seq(0,1.5,0.2), labels = scales::percent, limits = c(0,1.5)) +
  # 仅需一个geom_label调用,使用唯一键映射颜色
  geom_label(data=all_labels, aes(x=treatment, y=RATIO, label=perc, col=color_key), size=6, fill="white") +
  # 按唯一键独立分配每个分面下各处理的文本颜色
  scale_color_manual(values= c(
    "CV1_T1" = "Blue",
    "CV1_T2" = "Red",
    "CV1_T3" = "Blue",
    "CV2_T1" = "green",
    "CV2_T2" = "yellow",
    "CV2_T3" = "orange"
  )) +
  labs(x="treatment", y="Ratio (%)") +
  facet_wrap(~Genotype) + 
  theme(axis.title = element_text (face = "plain", size = 20, color = "black"),
        axis.text.x = element_text(size= 18),
        axis.text.y = element_text(size= 18),
        axis.line = element_line(size = 0.5, colour = "black"),
        legend.position = 'none')
# Windows系统可调用以下语句弹出指定尺寸的绘图窗口
# windows(width=9, height=5)
# 非Windows系统可替换为:
# dev.new(width=9, height=5)

内容的提问来源于stack exchange,提问作者J.K Kim

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 18:24:01