ggplot2中能否为geom_line的多个图例分别配置不同图例键?
为geom_line的多个图例配置不同图例键
要实现颜色图例用填充方块(便于区分数据集颜色)、线型图例用线条(展示变量线型差异)的效果,你可以在guides()中分别为每个美学映射指定对应的key_glyph参数,而非全局修改geom_line的键样式:
library(tidyverse) data_1 <- tibble( dataset = "Dataset 1", x = seq(0, 10), y1 = 2 * x, y2 = 3 * x ) data_2 <- tibble( dataset = "Dataset 2", x = seq(0, 10), y1 = 2.2 * x, y2 = 3.3 * x ) data <- bind_rows(data_1, data_2) |> pivot_longer(cols = c(y1, y2), names_to = "variable") ggplot( data = data, mapping = aes(x = x, y = value, colour = dataset, linetype = variable) ) + geom_line() + guides( colour = guide_legend( order = 1, key_glyph = "rect" # 为颜色图例设置填充方块键 ), linetype = guide_legend( key_glyph = "path" # 为线型图例保留默认线条键 ) ) + theme_bw()
关键说明
key_glyph是guide_legend()的专属参数,并非override.aes的子参数,这也是你之前尝试override.aes = list(key_glyph = "rect")无效的原因。- 使用
"rect"作为颜色图例的键样式,能更直观地展示颜色差异;"path"是geom_line默认的键样式,适合呈现线型变化。
自定义图例键(可选)
如果需要更个性化的图例键样式,可以自定义draw_key函数。例如创建带边框的颜色方块:
# 自定义带边框的方块键 draw_key_bordered_rect <- function(data, params, size) { grid::rectGrob( width = grid::unit(0.6, "npc"), height = grid::unit(0.6, "npc"), gp = grid::gpar( fill = data$colour, col = "black", # 添加边框颜色 lwd = 1 # 边框宽度 ) ) } ggplot( data = data, mapping = aes(x = x, y = value, colour = dataset, linetype = variable) ) + geom_line() + guides( colour = guide_legend( order = 1, key_glyph = draw_key_bordered_rect ), linetype = guide_legend(key_glyph = "path") ) + theme_bw()
内容的提问来源于stack exchange,提问作者David
相关产品推荐
相关产品推荐

