I have a dataframe which look like this :
From it, I want to make a plot which look like this :
I used ggplot and LibreOffice Draw to make the above plot. I wish to use ggplot only.
Here is a reproducible example :
library (dplyr)
n = 5
df = data.frame (
time = c(1 : n),
prediction_model1 = rnorm (n) %>% sort,
prediction_model2 = rnorm (n) %>% sort,
observed_values = rnorm (n) %>% sort
)
df_plot = df %>%
pivot_longer (cols = c (prediction_model1, prediction_model2), names_prefix = "prediction_", values_to = "happyness")
ggplot (df_plot) +
geom_point (aes (x = time, y = happyness, color = name), size = 2) +
geom_line (aes (x = time, y = happyness, color = name)) +
geom_point (aes (x = time, y = observed_values), shape = 5, size = 4) +
geom_line (aes (x = time, y = observed_values)) +
labs (color = "") +
theme (legend.position = "bottom")
>Solution :
You could map the shape and linetype aesthetics to a character value:
ggplot(df_plot, aes(x = time, y = happyness)) +
geom_point(aes(color = name), size = 2) +
geom_line (aes(color = name)) +
geom_point(aes(y = observed_values, shape = 'Observed values'), size = 3) +
geom_line (aes(y = observed_values, linetype = 'Observed values')) +
scale_shape_manual(name = NULL, values = 5) +
scale_linetype_manual(name = NULL, values = 1) +
labs(color = NULL) +
guides(linetype = guide_legend(keyheight = unit(20, 'mm'))) +
theme_classic(base_size = 16) +
theme(legend.position = "bottom",
axis.line = element_blank(),
panel.background = element_rect(fill = '#f3faff', color = 'gray60'))


