【问题标题】:How to change ggplot legend so that `fill` is a square and `linetype` is a line?如何更改ggplot图例以使“填充”是正方形而“线型”是线?
【发布时间】:2021-12-21 15:55:38
【问题描述】:

我有一个简单的情节:

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

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

如何更改图例以将 fill 显示为正方形,而将 linetype 模式显示为直线而不是正方形?

【问题讨论】:

标签: r ggplot2 legend


【解决方案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 package (v2.0.1) 于 2021-11-08 创建

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-01
    • 1970-01-01
    • 2022-11-22
    • 2020-08-13
    • 2019-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多