0

我有一个简单的情节:

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

reprex 包(v0.3.0)于 2021-11-08 创建

如何更改图例以显示fill为正方形,但linetype图案只是一条线而不是正方形?

4

1 回答 1

1

我不认为有办法在本地做到这一点。这是一个 hacky 解决方案,通过编写您自己的关键绘图函数并结合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)))

reprex 包于 2021-11-08 创建(v2.0.1)

于 2021-11-08T21:49:23.943 回答