在ggplot

时间:2019-06-17 20:42:18

标签: r ggplot2

我想使用以下a1, a2函数在ggplot中绘制两组垂直线,例如b1, b2r

myline = data.frame(vv = c(a1 = 25, a2 = 28, b1 = 52, b2 = 53))


set.seed(100)
d = data.frame(y = c(rnorm(100,5,1), rnorm(100, 2,4)), x = 1:200)
ggplot(data = d) + geom_line(aes(x, y), color = "steelblue") + 
  geom_vline(data = myline, aes(xintercept=as.numeric(vv)), col= 'red', size = 0.8)

我正在尝试将ab组以不同的颜色分开。我怎样才能做到这一点?非常感谢您的建议。

2 个答案:

答案 0 :(得分:2)

要使用不同颜色的垂直线,请使用vv作为对geom_vline的调用中的颜色。然后使用scale_color_manual设置选择的颜色。
另请注意,在设置as.numeric(vv)美观度的值时,不需要xinterceptstr(myline)将显示vv已经是数字了。

ggplot(data = d, aes(x, y)) + 
  geom_line(color = "steelblue") + 
  geom_vline(data = myline, 
             aes(xintercept = vv, color = factor(vv)),
             size = 0.4) +
  scale_color_manual(values = c("coral", "coral4", "orange", "orange4"))

enter image description here

答案 1 :(得分:1)

这是你的追求吗?

library("dplyr")

myline = data.frame(vv = c(25, 28, 52, 53),
                    xx = c("a1", "a2", "b1", "b2"))

myline <- as_tibble(myline) %>%
  mutate(group = substr(xx,1,1))

set.seed(100)
d = data.frame(y = c(rnorm(100,5,1), rnorm(100, 2,4)), x = 1:200)

ggplot(data = d) + geom_line(aes(x, y), color = "steelblue") + 
  geom_vline(data = myline, aes(xintercept=as.numeric(vv), col=group), size = 0.8)