SiH
SiH

Reputation: 1546

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

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

Upvotes: 2

Views: 376

Answers (1)

Martin C. Arnold
Martin C. Arnold

Reputation: 9658

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

Upvotes: 3

Related Questions