ivan
ivan

Reputation: 93

Change color for just part of a line

I have this data.

# A tibble: 200 x 4
   day        dayofweek users   weekend
   <date>     <chr>     <int>   <fct>
 1 2018-08-01 Wednesday    5    FALSE
 2 2018-08-02 Thursday     8    FALSE
 3 2018-08-03 Friday       20   FALSE
 4 2018-08-04 Saturday     12   TRUE
 5 2018-08-05 Sunday       88   TRUE
 6 2018-08-06 Monday       1    FALSE
..   ...       ...         ..   ...

I'd like to make a line chart with it. And I'd like to highlight the parts of the chart that are on the weekends by showing them as a different color.

I tried this.

tibble %>% 
  ggplot(aes(day, users, group = weekend)) +
  geom_line()

And this.

tibble %>% 
  ggplot(aes(day, users, fill = weekend)) +
  geom_line()

And this.

tibble %>% 
  ggplot(aes(day, users, color = weekend)) +
  geom_line()

It just creates new lines.

How do I change just a part of the existing line without making any new ones?

Upvotes: 3

Views: 770

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388817

One option is

library(ggplot2)
ggplot(df) + aes(day, users, color = weekend, group = 1) + geom_line()

enter image description here

Here, lines in green color are weekends whereas those in red are weekdays.

data

df <- structure(list(day = structure(1:7, .Label = c("2018-08-01", 
"2018-08-02", "2018-08-03", "2018-08-04", "2018-08-05", "2018-08-06", 
"2018-08-07"), class = "factor"), dayofweek = structure(c(7L, 
5L, 1L, 3L, 4L, 2L, 6L), .Label = c("Friday", "Monday", "Saturday", 
"Sunday", "Thursday", "Tuesday", "Wednesday"), class = "factor"), 
users = c(5L, 8L, 20L, 12L, 88L, 1L, 10L), weekend = c(FALSE, 
FALSE, FALSE, TRUE, TRUE, FALSE, FALSE)), class = "data.frame", 
row.names = c("1", "2", "3", "4", "5", "6", "7"))

Upvotes: 2

Related Questions