ggplots2:根据另一个向量添加点的更改颜色。

时间:2016-04-13 20:58:48

标签: r ggplot2

嗨,目前我是一个情节,我可以根据某些截止值改变点的颜色

library(ggplot2)
library(ggrepel)

x = c(0.8846, 1.1554, 0.9317, 0.9703, 0.9053, 0.9454, 1.0146, 0.9012, 
      0.9055, 1.3307)
y = c(0.9828, 1.0329, 0.131, 1.3794, 0.9273, 0.3605, 1.0259, 0.9542, 
      0.9717, 0.9357)
z= c("a", "b", "c", "d", "e", "f", 
     "g", "h", "i", "j")


df = data.frame(x = x, y = y, z = z)
z <- as.vector(df$z)
ggplot(data = df, aes(x = x, y = y)) + theme_bw() + 


  geom_text_repel(data = subset(df, y > 1.3), aes(label = z), 
                  box.padding = unit(0.45, "lines")) +

  geom_point(aes(colour = cut(y, c(-Inf,0.2,0.5,Inf))), size = 3) +
  # set color scales 
  scale_color_manual(
    name = "p-values",
    values = c("(-Inf,0.2]" = "blue",
               "(0.2,0.5]" = "red",
               "(0.5, Inf]" = "grey"))

图表看起来像这样, enter image description here

然而,有一种方法可以根据另一组矢量改变颜色。 比如说我有,

x2<-c("a","b")
x3<-c("f")

我可以设置它,以便只有x2中的点是红色,x3是蓝色而其余的是灰色吗?提前致谢!

1 个答案:

答案 0 :(得分:2)

你有正确的想法。只需添加一个指定条件的列。

df$condition <- "others"
df[df$z %in% c("a","b"), "condition"] <- "x2"
df[df$z %in% c("f"), "condition"] <- "x3"

ggplot(data = df, aes(x = x, y = y, colour= condition)) + theme_bw() + 
  geom_point(size = 3) +
  # set color scales 
  scale_color_manual(
    name = "p-values",
    values = c("x2" = "red",
               "x3" = "blue",
               "others" = "grey"))

enter image description here