Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Separated legend between two variables in ggplot

I have a dataframe which look like this :

enter image description here

From it, I want to make a plot which look like this :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enter image description here

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

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading