Search code examples
rggplot2themesshapeslegend-properties

Change manually the shape of a legend ggplot2


I've been customizing themes, lines, and colors in the following plot

library(dplyr)
library(ggplot2)
library(readr)
library(zoo) 

cvper <-  read.csv("https://cloud.minsa.gob.pe/s/Y8w3wHsEdYQSZRp/download", stringsAsFactors = FALSE)
nuevos_cvper <- cvper %>% 
  group_by(FECHA_RESULTADO) %>%
  arrange(desc(FECHA_RESULTADO)) %>%
  summarize (casos_x_dia= n()) %>% 
  mutate(media_movil = rollmean(casos_x_dia, k=7, fill = NA, align = "right"))

prueba_legend <- ggplot(nuevos_cvper) + 
  geom_line(aes (x = FECHA_RESULTADO, y = media_movil, color = "media_movil"), size = 1.5) +
  geom_line(aes (x = FECHA_RESULTADO, y = casos_x_dia, color = "casos_x_dia"), linetype = "dashed" ) +
  geom_point (aes(x = FECHA_RESULTADO, y = casos_x_dia, color = "casos_x_dia")) +
  scale_colour_manual("", values = c("media_movil"="#CF3721", "casos_x_dia"="#31A9B8", 
                                 "casos_x_dia"="#31A9B8")) +
  theme_bw () + theme(legend.position="bottom")

prueba_legend 

It shows a legend with short lines. I want to change those lines to circles. I´ve tried with scale_shape_manual, but it doesn't work. Is there a way?


Solution

  • Since one of the more recent ggplot2 versions (make sure you update via install.packages("ggplot2")), the argument key_glyph= can be used to specify the draw_key function that should be used to draw the legend glyphs for a given geom and aesthetic. See here for some more information and examples of usage; however, I will demonstrate with the following example using mtcars and ggplot2 version 3.3.2:

    ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, color=Species)) +
      geom_line(key_glyph = "point")
    

    enter image description here

    You may notice as I did that the point size is a bit small for my taste. That can be adjusted by using override.aes= via the guide_legend() function specified for the color aesthetic to make those points a bit bigger.

    ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, color=Species)) +
      geom_line(key_glyph = "point") +
      guides(color=guide_legend(override.aes = list(size=3)))
    

    enter image description here