How to change ggplot legend so that `fill` is a square and `linetype` is a line?

I have a simple plot:

library(ggplot2)
ggplot(mtcars, aes(mpg, disp, fill = "fill")) +
  geom_violin(aes(linetype = "pattern"), 
              key_glyph = draw_key_path)

Created on 2021-11-08 by the reprex package (v0.3.0)

How can I change the legend to show the fill as a square, but the linetype pattern as just a line instead of a square?

library(tidyverse)

mtcars %>%
  mutate(fill="1") %>%  
  ggplot(aes(x=mpg, y=disp, fill = fill)) +
  geom_violin(aes(linetype = "pattern"), 
              key_glyph = draw_key_path)+
  guides(fill = guide_legend(
    override.aes = list(linetype = 0)))+
  theme(legend.key =element_rect(fill=c("salmon")))+
  scale_fill_manual(name = "fill legend",
                    values = 'salmon',
                    labels = c('fill here'))

image

I could not find a way to separate the legend.key.
If anyone else knows how to do this, please let me know.

1 Like