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

problem in geom_line when colored based on a categorical variable

I want to create "a single line plot" of speed vs time. I wish to color the line based on the categ.

categ is a factor variable which can take value – 0, 1, 2.

But I am getting three line plots based on categ

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

enter image description here

library(tidyverse)

tbl <- tibble(time = 1:100,
              speed = 20 + runif(100),
              categ = factor(rbinom(n = 100, size = 3, prob = 0.1)))


ggplot(data = tbl,
       aes(x = time,
           y = speed,
            color = categ)) + 
  geom_line(size = 1) + 
  theme_bw()

>Solution :

For this to work the different colored segments need to belong to the same group:

ggplot(data = tbl,
       aes(x = time, y = speed, color = categ, group = 1)) + 
  geom_line(size = 1) + 
  theme_bw()

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