score324
score324

Reputation: 717

Draw two groups of multiple vertical lines in ggplot

I want to drew the two groups such as a1, a2 and b1, b2 of vertical lines in ggplot using the following r functions.

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)

I am trying to separate the a and b groups in different colors. How can I do that? Thank you very much for your suggestions.

Upvotes: 2

Views: 574

Answers (2)

Rui Barradas
Rui Barradas

Reputation: 76663

To have the vertical lines of different colors, use vv as the color in the call to geom_vline. Then set the colors of choice with scale_color_manual.
Note also that there is no need for as.numeric(vv) when setting the value for the xintercept aesthetic, str(myline) will show vv already is numeric.

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

Upvotes: 2

bjorn2bewild
bjorn2bewild

Reputation: 1019

Is this what you are after?

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)

Upvotes: 1

Related Questions