ggplot2:仅在满足条件时在点旁边添加文本

时间:2016-04-12 22:49:01

标签: 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.931, 1.3794, 0.9273, 0.9605, 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)
ggplot(data = df, aes(x = x, y = y)) + theme_bw() + 
geom_text_repel(aes(label = z), 
box.padding = unit(0.45, "lines")) +
geom_point(colour = "green", size = 3)

这会给我一些看起来像这样的东西。 enter image description here

然而,如果我只希望文字出现,如果y&gt; 1.3仅在这种情况下&#34; d&#34;将被贴上标签。有任何想法吗?提前致谢。

2 个答案:

答案 0 :(得分:3)

geom_text_repel参数中对数据进行子集。

e.g。

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.931, 1.3794, 0.9273, 0.9605, 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)
ggplot(data = df, aes(x = x, y = y)) + theme_bw() + 
  # Subset the data as it relates to the y value
  geom_text_repel(data = subset(df, y > 1.3), aes(label = z), 
                  box.padding = unit(0.45, "lines")) +
  geom_point(colour = "green", size = 3)

Graph with only d point labeled

答案 1 :(得分:1)

如果您在data来电中指定geom_text_repel

ggplot(data = df, aes(x = x, y = y)) + theme_bw() + 
    geom_text_repel(data = df[which(df$y > 1.3),], 
                    aes(label = z), 
                    box.padding = unit(0.45, "lines")) +
    geom_point(colour = "green", size = 3)

enter image description here