With a data sample as follows:
df <- structure(list(date = structure(c(18901, 18902, 18903, 18904,
18905, 18906, 18907, 18908, 18909, 18910, 18911, 18912, 18913,
18914), class = "Date"), value = c(190.3, 174.9, 163.2, 168.4,
168.6, 168.2, 163.5, 161.6, 172.9, 166.5, 175.2, 197.7, 212.1,
177.9), type = c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 3L,
3L, 3L, 3L)), row.names = c(NA, -14L), class = "data.frame")
First I convert type
and date
to appropriate data type:
df$type <- as.factor(df$type)
df$date <- as.Date(df$date)
I'm try to draw this time series data simultaneously based on type
with different colours.
The problem is I can't set customized colours and gap between areas are a little bit large.
ggplot(data=df, aes(x=date, y=value, group=type))
geom_area(fill=df$type, alpha=0.4)
geom_line(color=df$type, size=1)
geom_point(size=2, color=df$type)
scale_color_manual(values=c("gray", "red", "blue"))
Out:
How could reproduice a figure similar to effect below? Sincere thanks.
CodePudding user response:
For the colors, I'd suggest:
df$type = as.factor(df$type)
ggplot(df, aes(x=date, y=value, group=type,
color = type, fill = type))
geom_area(alpha=0.4)
geom_line(size=1)
geom_point(size=2)
scale_color_manual(values=c("1" = "gray", "2" = "red", "3" = "blue"),
aesthetics = c("color", "fill"), name = "type")
EDIT - to remove the gaps, we could repeat the first entries of each type
and assign them to the prior type
.
library(dplyr)
df %>%
group_by(type) %>%
filter(row_number() == 1) %>%
ungroup() %>%
mutate(type = lag(type),
date = date - 0.0001) %>% # w/o this the values stack at boundaries
bind_rows(df) %>%
ggplot(aes(x=date, y=value, group=type,
color = type, fill = type))
...