【问题标题】:ggplots2: add change color of points based on another vector.ggplot2:根据另一个向量添加点的颜色变化。
【发布时间】:2016-04-14 05:27:50
【问题描述】:

您好,目前我有一个可以根据某些截止值更改点颜色的图

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"))

图表看起来像这样,

但是有一种方法可以根据另一组向量更改颜色。 例如说我有,

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

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

【问题讨论】:

  • 喜欢ggplot(data = df, aes(x = x, y = y, color = ifelse(z %in% x2, "red", ifelse(z %in% x3, "blue", "grey")))) + scale_color_identity() + geom_point(size = 3)?

标签: r ggplot2


【解决方案1】:

你的想法是对的。只需创建一个额外的列来指定您的条件。

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"))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-03
    • 1970-01-01
    • 2021-08-16
    • 2020-07-23
    相关资源
    最近更新 更多