just_rookie
just_rookie

Reputation: 893

ggplot2: coloring segments of single line with different colors

I would like to plot two lines and then color segments of a single line with different colors. Here is a simple code:

temp <- data.frame(x = c(2, 4, 5, 5, 7, 6, 7, 8, 10, 9),
            y = c(3, 8, 4, 8, 8, 4, 9, 12, 5, 1),
            line = c('a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'b', 'b'),
            color = c('c', 'c', 'd', 'd', 'd', 'c', 'c', 'c', 'd', 'd'))

ggplot() +
  geom_line(aes(x, y, linetype = line, color = ???), data = temp)

I want to color segments of each line using the color factor. Any help? Thank you in advance!

Upvotes: 0

Views: 2606

Answers (1)

Likan Zhan
Likan Zhan

Reputation: 1076

Does this graph solve you problem?

ggplot() + geom_line(aes(x, y, group = line, color = color), data = temp)

Upvotes: 4

Related Questions