如何更改 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 package (v0.3.0)
于 2021-11-08 创建
如何更改图例以将 fill
显示为正方形,但将 linetype
图案显示为一条线而不是正方形?
我认为没有办法在本地执行此操作。这是一个 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 创建
我有一个简单的情节:
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
图案显示为一条线而不是正方形?
我认为没有办法在本地执行此操作。这是一个 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 创建