我有这样的df:
set.seed(123)
df <- data.frame(Delay=rep(-5:6, times=8, each=1),
ID= rep(c("A","B","C","D"), times=1, each=24),
variable=rep(c("R2","SE"), times=4, each=12),
value=c(0.3,0.4,0.51,0.58,0.64,0.78,0.68,0.63,0.54,0.45,0.32,0.22,0.78,0.68,0.59,0.55,0.47,0.35,0.28,0.41,0.50,0.58,0.63,0.73,0.3,0.4,0.51,0.58,0.64,0.78,0.68,0.63,0.54,0.45,0.32,0.22,0.78,0.68,0.59,0.55,0.47,0.35,0.28,0.41,0.50,0.58,0.63,0.73,0.3,0.4,0.51,0.58,0.64,0.78,0.68,0.63,0.54,0.45,0.32,0.22,0.78,0.68,0.59,0.55,0.47,0.35,0.28,0.41,0.50,0.58,0.63,0.73,0.3,0.4,0.51,0.58,0.64,0.78,0.68,0.63,0.54,0.45,0.32,0.22,0.78,0.68,0.59,0.55,0.47,0.35,0.28,0.41,0.50,0.58,0.63,0.73))
df$ID <- as.factor(df$ID)
df$variable <- as.factor(df$variable)
Plot<- ggplot(df[df$ID=="B",], aes(x=Delay, y=value, group=variable, colour=variable)) +
geom_point(size=1) +
geom_line () +
theme_hc() +
theme(legend.position="right") +
labs(x= '\nDelay',y=expression(R^{2})) +
guides(color=guide_legend(override.aes=list(fill=NA))) +
scale_x_continuous(breaks=seq(-5,5,1)) +
scale_color_jco()
Plot
我只绘制的数据B
。
我想为的最小值添加一条SE
垂直线,为的最大值添加一条垂直线R2
。我希望线条的颜色与变量的颜色相同。但是,我不知道该怎么做。垂直线的颜色为黑色,如下图所示,所以我不知道如何指示我想要我以前使用的特定颜色。
Plot <- Plot + geom_vline(xintercept = 0)
Plot
有谁知道如何使用与变量相同的颜色来添加两条垂直线?
我认为@ r2evans解决您的特定问题的方法是正确的。但是,要回答有关如何从已应用的色标中检索颜色的更一般的问题(例如,如果要修改颜色等),可以ggbuild
使用以下方法,无需进行操作即可获得:
Plot$scales$get_scales("colour")$palette(2)
[1] "#0073C2FF" "#EFC000FF"
因此,我们可以这样做:
# Get colours
my_blue <- Plot$scales$get_scales("colour")$palette(2)[1]
my_yellow <- Plot$scales$get_scales("colour")$palette(2)[2]
# Get index of max R2 and min SE
maxR2 <- which.max(df$value[df$ID == "B" & df$variable == "R2"])
minSE <- which.min(df$value[df$ID == "B" & df$variable == "SE"])
# Get value of Delay at maxR2 and minSE
D_R2 <- df$Delay[df$ID == "B" & df$variable == "R2"][maxR2]
D_SE <- df$Delay[df$ID == "B" & df$variable == "SE"][minSE]
# Plot lines at the correct positions and with the desired colours
Plot + geom_vline(aes(xintercept = D_R2), colour = my_blue) +
geom_vline(aes(xintercept = D_SE), colour = my_yellow)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句