仅更改部分线条的颜色

时间:2019-04-19 03:46:56

标签: r ggplot2

我有这个数据。

# 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
..   ...       ...         ..   ...

我想用它制作折线图。我想通过显示为不同的颜色来突出显示周末的图表部分。

我尝试过这个。

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

还有这个。

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

还有这个。

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

它只是创建新行。

如何仅更改现有生产线的一部分而不进行任何新生产?

1 个答案:

答案 0 :(得分:2)

一个选项是

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

enter image description here

在这里,绿色的线条是周末,而红色的线条是工作日。

数据

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