Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  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 ?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading