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

Time:11-10

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?

CodePudding user response:

I don't think there is a way to do this natively. Here is a hacky solution by writing your own key drawing function in combination with guide_legend(override.aes = list(...)).

library(ggplot2)
#> Warning: package 'ggplot2' was built under R version 4.1.1

my_key <- function(data, params, size) {
  if (all(is.na(data$fill))) {
    draw_key_path(data, params, size)
  } else {
    draw_key_polygon(data, params, size)
  }
}

ggplot(mtcars, aes(mpg, disp, fill = "fill"))  
  geom_violin(aes(linetype = "pattern"),
              key_glyph = my_key)  
  guides(linetype = guide_legend(override.aes = list(fill = NA)))

Created on 2021-11-08 by the reprex package (v2.0.1)

  • Related