[英]How to put boxes around alpha values in legend for ggplot2
我想在图例中的 alpha 值周围放置黑框,以便实际显示最小值 (70)。 需要明确的是:围绕代表每个 alpha 值的每个单独的正方形,而不是围绕整个图例。
mtcars
test_plot <- ggplot() +
geom_point(data = mtcars,
aes(x = wt, y = mpg,
alpha = disp,
size = hp),
fill = 'black',
shape = 21) +
geom_point(data = mtcars,
aes(x = cyl, y = mpg,
size = hp),
fill = 'black',
shape = 1) +
xlab("Weight") + ylab("MPG") +
labs(size = "Horsepower:", alpha = "Displacement:") +
scale_size_continuous(range = c(1,10), breaks= c(50, 100, 150, 200, 250, 300, 350)) +
scale_alpha_continuous(range = c(0,1),
breaks= c(71.1, 100, 200, 300, 400, 500),
labels = c(70, 100, 200, 300, 400, 500)) +
guides(size = guide_legend(override.aes = list(shape = 1)),
alpha = guide_legend(override.aes = list(shape = 22, color = 'black')))
test_plot
问题是alpha
值同时应用于图例键的fill
和边框color
。 不幸的是,我不知道有一个简单的解决方案。 获得所需结果的一种方法是操作gtable
。
library(ggplot2)
p <- ggplot() +
geom_point(data = mtcars,
aes(x = wt, y = mpg,
alpha = disp,
size = hp),
fill = 'black',
shape = 21) +
geom_point(data = mtcars,
aes(x = cyl, y = mpg,
size = hp),
fill = 'black',
shape = 1) +
xlab("Weight") + ylab("MPG") +
labs(size = "Horsepower:", alpha = "Displacement:") +
scale_size_continuous(range = c(1,10), breaks= c(50, 100, 150, 200, 250, 300, 350)) +
scale_alpha_continuous(range = c(0,1),
breaks= c(71.1, 100, 200, 300, 400, 500),
labels = c(70, 100, 200, 300, 400, 500)) +
guides(size = guide_legend(override.aes = list(shape = 1)),
alpha = guide_legend(override.aes = list(shape = 22, color = 'black')))
library(gtable)
library(grid)
g <- ggplotGrob(p)
for (i in c(4, 6, 8, 10, 12)) { # Indices of legend keys
# guide-box is element 15 in the gtable
# alpha legend if the first element of the "guide-box"
gp <- g$grobs[[15]]$grobs[[1]]$grobs[[i]]$gp
gp <- modifyList(gp, list(col = "black"))
g$grobs[[15]]$grobs[[1]]$grobs[[i]]$gp <- do.call(grid::gpar, gp)
}
grid.newpage()
grid.draw(g)
Map 变量fill
而不是alpha
,具有一些具有边缘的形状,并使用scale_fill_gradient*
和 colors 变化的 alpha。 使用stroke
来控制边框的大小。
我简化了您的示例以突出代码的相关点:
ggplot(mtcars, aes(wt, mpg)) +
geom_point(aes(fill = disp), shape = 21, size = 10, stroke = 1e-10) +
scale_fill_gradient(low = alpha("black", 0), high = alpha("black", 1), guide = "legend") +
guides(fill = guide_legend(override.aes = list(size = 6, stroke = .5)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.