[英]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.