Home > Software design >  problem in geom_line when colored based on a categorical variable
problem in geom_line when colored based on a categorical variable

Time:11-23

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

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()

CodePudding user response:

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

  • Related