rggplot2legend

How to change line height in legend?


How to change line height in legend ? In geom_line(size=2) ,change size can change line height both in plot and legend , how to change only legend line size ?

library(tidyverse)
plot_data <- data.frame(my_date= seq.Date(as.Date('2023-1-1'),
                                          as.Date('2023-12-31'),'1 day'),
                        my_value=rnorm(365)) %>% 
  mutate(my_month = lubridate::month(my_date))


plot_data %>% ggplot(aes(x = my_date,y=my_value,
                         color= factor(my_month))) +
  geom_line(size=2)+
  guides(color = guide_legend(nrow=1,title='color'))+
  theme(legend.position = 'top')

enter image description here


Solution

  • To change the linewidth (or other aesthetics) in the legend only you can use the override.aes= argument of guide_legend:

    Note: I switched to linewidth instead of size.

    library(ggplot2)
    
    ggplot(plot_data, aes(
      x = my_date, y = my_value,
      color = factor(my_month)
    )) +
      geom_line(linewidth = 2) +
      guides(
        color = guide_legend(
          nrow = 1, title = "color",
          override.aes = list(linewidth = 4)
        )
      ) +
      theme(legend.position = "top")