[英]ggplot2: how to separate geom_polygon and geom_line in legend keys?
[英]Separate symbol and line keys in ggplot2 joined legend
我有一個類似於以下的 plot,它同時具有到同一變量的 l.netype 和 shape 映射。 我想保留連接的圖例,但希望圖例中的點在線上方,這樣我可以更好地看到 l.netype。 任何幫助表示贊賞。
library(tidyverse)
library(grid)
ggplot(mtcars, aes(gear, mpg,
shape = factor(cyl),
linetype = factor(cyl),
color = factor(cyl))) +
geom_point(size = 2) +
stat_summary(fun = mean, geom = "line", size = 1)+
theme(legend.key.width = grid::unit(0.5, "inch"))
感謝@starja 的提示,
draw_key_point2 <- function (data, params, size) {
`%||%` <- ggplot2:::`%||%`
if (is.null(data$shape)) {
data$shape <- 19
}
else if (is.character(data$shape)) {
data$shape <- ggplot2:::translate_shape_string(data$shape)
}
stroke_size <- data$stroke %||% 0.5
stroke_size[is.na(stroke_size)] <- 0
grid::pointsGrob(0.5, 0.9, pch = data$shape,
gp = grid::gpar(col = alpha(data$colour %||% "black", data$alpha),
fill = alpha(data$fill %||% "black", data$alpha),
fontsize = (data$size %||% 1.5) * .pt + stroke_size * .stroke/2,
lwd = stroke_size * .stroke/2))
}
ggplot(mtcars, aes(gear, mpg,
shape = factor(cyl),
linetype = factor(cyl),
color = factor(cyl))) +
# geom_point(size = 2) +
geom_point(size = 2, key_glyph = draw_key_point2) +
stat_summary(fun = mean, geom = "line", size = 1)+
theme(legend.key.width = grid::unit(0.5, "inch"))
請注意,此 function 需要兩個未導出ggplot2函數( `%||%`和translate_shape_string ),這將導致此 function(如果添加到包中)無法通過 R 檢查。 將這些函數的當前版本復制到您的 package 代碼中並不難,有效地及時凍結了它們的主體,認識到您需要通過 ggplot2 中的更改/錯誤修復使您的 package 保持最新。
這個 function 將一組硬編碼默認值 ( 0.5, 0.5 ) 替換為另一組硬編碼默認值 ( 0.5, 0.9 )。 顯然還有其他方法可以解決這個問題,例如 function 返回 function:
draw_key_point3 <- function(...) {
function(data, params, size) {
`%||%` <- ggplot2:::`%||%`
dots <- list(...)
colour <- dots$colour %||% dots$color %||% data$colour %||% "black"
shape <- dots$shape %||% data$shape %||% 19L
alpha <- dots$alpha %||% data$alpha
if (is.character(shape)) {
shape <- ggplot2:::translate_shape_string(shape)
}
stroke_size <- dots$stroke %||% data$stroke %||% 0.5
stroke_size[is.na(stroke_size)] <- 0
grid::pointsGrob(dots$x %||% 0.5, dots$y %||% 0.5, pch = shape,
gp = grid::gpar(col = alpha(colour, alpha),
fill = alpha(dots$fill %||% data$fill %||% "black", alpha),
fontsize = (dots$size %||% data$size %||% 1.5) * .pt + stroke_size * .stroke/2,
lwd = stroke_size * .stroke/2))
}
}
ggplot(mtcars, aes(gear, mpg,
shape = factor(cyl),
linetype = factor(cyl),
color = factor(cyl))) +
geom_point(size = 2, key_glyph = draw_key_point3(x=0.5, y=0.1, shape = 18)) +
stat_summary(fun = mean, geom = "line", size = 1)+
theme(legend.key.width = grid::unit(0.5, "inch"))
可以在其中設置任何鍵/圖例字形組件(x、y、顏色、形狀、alpha、填充、大小)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.