如何重命名基于多因子水平交互的ggplot图例?
解决ggplot2因子交互图例标题修改问题
你遇到的问题是使用interaction(f1,f2)作为颜色和线型的映射后,图例标题默认显示为interaction(f1.f2),下面提供两种简单的修改方法:
方法1:手动设置刻度或图例的名称
因为你同时绑定了color和linetype到同一个交互变量,所以需要给对应的刻度设置统一的名称,或者通过guides()统一指定图例标题:
方式1-1:在刻度函数中设置name参数
library(ggplot2) # 示例数据框 x <- rep(seq(100, 120, 10), each = 4) f1 <- rep(1:2, each = 2, times = 3) # 因子1,2个水平 f2 <- rep(1:2, each = 1, times = 6) # 因子2,2个水平 y <- c(6, 2, 2, 1, 14, 5, 5, 2, 22, 6, 8, 1) df <- data.frame(x, f1, f2, y) p <- ggplot(df, aes(x = x, y = y)) + geom_line(aes(color = interaction(f1, f2), linetype = interaction(f1, f2))) + scale_linetype_manual(values = c("dotted", "dotdash", "longdash", "solid"), name = "f1.f2") + # 给线型刻度设置标题 scale_color_discrete(name = "f1.f2") + # 给颜色刻度设置标题 theme_minimal() p
方式1-2:用guides()统一设置图例标题
这种方式更简洁,不需要分别修改两个刻度:
p <- ggplot(df, aes(x = x, y = y)) + geom_line(aes(color = interaction(f1, f2), linetype = interaction(f1, f2))) + scale_linetype_manual(values = c("dotted", "dotdash", "longdash", "solid")) + guides( color = guide_legend(title = "f1.f2"), linetype = guide_legend(title = "f1.f2") ) p
方法2:提前在数据框中创建命名的交互列
直接在数据里生成名为f1.f2的交互列,后续绘图时直接映射这个列,图例标题会自动使用列名,更直观:
library(ggplot2) # 示例数据框,提前创建交互列 x <- rep(seq(100, 120, 10), each = 4) f1 <- rep(1:2, each = 2, times = 3) f2 <- rep(1:2, each = 1, times = 6) y <- c(6, 2, 2, 1, 14, 5, 5, 2, 22, 6, 8, 1) df <- data.frame(x, f1, f2, y) df$`f1.f2` <- interaction(df$f1, df$f2) # 创建指定名称的交互列 p <- ggplot(df, aes(x = x, y = y)) + geom_line(aes(color = `f1.f2`, linetype = `f1.f2`)) + scale_linetype_manual(values = c("dotted", "dotdash", "longdash", "solid")) + theme_minimal() p
内容的提问来源于stack exchange,提问作者Herb
相关产品推荐
相关产品推荐

