在 R boxplot ggplot2 中对特定 X 变量进行着色

Shading a particular X variable in R boxplot ggplot2

我是 RF 的新手,非常感谢您的帮助,在下面的箱线图查询中,我只想遮蔽 g3(对我来说最重要),我应该在以下代码后添加什么请仅遮蔽 'g3'

library(ggplot2)

a<-rep(c("g1","g2","g3","g4","g5","g6"),each=10) 
b<-rnorm(60)

d1<-data.frame(a,b)

ggplot(d1)+geom_boxplot(aes(x=a,y=b))

这应该有效。

+ geom_boxplot(aes(x=a,y=b, fill = a == "g3")) + 
  scale_fill_manual(values = c("grey", "green"))

https://ggplot2.tidyverse.org/ 将对您入门有很大帮助。

这是一个类似的解决方案,允许您根据需要自定义图例。

library(ggplot2)

a<-rep(c("g1","g2","g3","g4","g5","g6"),each=10) 
b<-rnorm(60)

d1<-data.frame(a,b)

ggplot(d1) +
  geom_boxplot(aes(x=a,y=b, fill=(ifelse(a=="g3","Shaded","Not Shaded"))), show.legend = TRUE) +
  scale_fill_manual(name = "Legend Name", values=c("grey","orange"))

如果要删除图例,只需更新 show.legend = FALSE:

ggplot(d1) +
  geom_boxplot(aes(x=a,y=b, fill=(ifelse(a=="g3","Shaded","Not Shaded"))), show.legend = FALSE) +
  scale_fill_manual(name = "Legend Name", values=c("grey","orange"))