Home > Blockchain >  geom_line() with x as factor and a grouping variable for color
geom_line() with x as factor and a grouping variable for color

Time:02-11

I have the following reproducible data :

d <- data.frame(ATB = rep(c("ATB1", "ATB2"), each = 4), 
            status = rep(rep(c("S", "R"), each = 2), 2), 
            season = rep(c("Winter", "summer"), 4),
            n = c(239,284,113,120,229,269,127,140)
            ) 

I am trying to draw points for the count n for each line by season, the color being the variable ATB, and to link each point according to the ATB and to the status from one season value to another (ATB1 S winter linked to ATB1 S summer). Here is the plot I am trying to get: desired plot

Until now I managed to draw the points but not the lines.

  ggplot(d, aes(x=season, y = n))  
    geom_point(aes(color = ATB))  
    geom_line(aes(color = ATB, linetype = status))

Here is the plot I managed to get

I tried group = 1 in each aes, but it didn't work.

Is there a way to obtain the plot ?

CodePudding user response:

You need to group by the interaction of ATB and status, otherwise you are not correctly telling ggplot which points to connect:

  ggplot(d, aes(x=season, y = n))  
    geom_point(aes(color = ATB))  
    geom_line(aes(color = ATB, linetype = status, 
                  group = interaction(ATB, status)))  
    scale_linetype_manual(values = c(2, 1))

enter image description here

  • Related