繁体   English   中英

如何更改ggplot图例,以便`fill`是一个正方形而`linetype`是一条线?

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

我有一个简单的情节:

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 月 8 日创建

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

我认为没有办法在本地做到这一点。 这是通过编写自己的关键绘图函数与guide_legend(override.aes = list(...))结合使用的hacky 解决方案。

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 包(v2.0.1) 于 2021 年 11 月 8 日创建

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM