ggplot2:为geom_path与geom_point组合图设置单个重命名图例
解决方案
问题出在你同时使用了shape、fill、colour三个美学映射绑定同一分组变量,但仅修改了shape的图例标题,导致图例拆分。要合并成单个带"Sample"标题的图例,只需统一所有相关美学映射的图例名称即可,以下是两种简洁方法:
方法一:通过labs()统一设置所有相关美学的标题
直接在labs()里同时指定shape、fill、colour的标题为"Sample",ggplot会自动将同变量的图例合并:
ggplot(great_hollow, aes(x = d15N, y = Sample_ordered)) + geom_path(aes(group = Species_ordered, colour = Species_ordered)) + geom_point(aes(shape = Species_ordered, fill = Species_ordered), colour = "black", size = 3) + scale_shape_manual(values = c(21, 22, 24, 21, 23, 25)) + # 同时设置三个美学的图例标题为Sample labs(shape = "Sample", fill = "Sample", colour = "Sample") + facet_wrap(~Type, scales = "fixed") + ggtitle(expression(paste(delta^{15},"N Values by Site and Trophic Level"))) + scale_x_continuous(expression(paste(delta^{15}, "N (‰ VS air)"))) + scale_y_discrete(limits=rev) + theme_bw() + theme(plot.title = element_text(hjust = 0.5), axis.title.y = element_blank(), plot.background = element_rect(color = 1, linewidth = 1), plot.margin = margin(t = 10, r = 10, b = 10, l = 10))
方法二:在手动scale中统一设置name参数
如果你需要手动指定fill和colour的颜色,可在对应的scale函数里设置name="Sample",同时给shape的scale也设置名称,同样能合并图例:
ggplot(great_hollow, aes(x = d15N, y = Sample_ordered)) + geom_path(aes(group = Species_ordered, colour = Species_ordered)) + geom_point(aes(shape = Species_ordered, fill = Species_ordered), colour = "black", size = 3) + # 给shape的scale设置名称 scale_shape_manual(name = "Sample", values = c(21, 22, 24, 21, 23, 25)) + # 自定义颜色时可指定values,仅统一名称则留空values用默认配色 scale_colour_manual(name = "Sample") + scale_fill_manual(name = "Sample") + facet_wrap(~Type, scales = "fixed") + ggtitle(expression(paste(delta^{15},"N Values by Site and Trophic Level"))) + scale_x_continuous(expression(paste(delta^{15}, "N (‰ VS air)"))) + scale_y_discrete(limits=rev) + theme_bw() + theme(plot.title = element_text(hjust = 0.5), axis.title.y = element_blank(), plot.background = element_rect(color = 1, linewidth = 1), plot.margin = margin(t = 10, r = 10, b = 10, l = 10))
额外修正:初始aes语法错误
你原代码中ggplot(great_hollow, aes(x = d15N, y = Sample_ordered), color = Species_ordered)的color = Species_ordered写在了aes()外面,属于无效语法,已在上述代码中修正,将分组变量的映射放在对应geom的aes()内。
内容的提问来源于stack exchange,提问作者theyhem
相关产品推荐
相关产品推荐

