R语言ggplot2如何分别设置两个图例位置并移除重复图例
问题解决方法
你之前代码出现重复图例的核心原因是:提取Mutations图例时没有关闭Regions对应的fill图例,导致提取的右侧图例同时包含两个内容,和主图底部的Regions图例重复。可通过以下两种方案解决:
方案1:使用ggplot原生单图例位置设置(推荐,版本≥3.5.0,无需拼接)
直接调整原绘图代码,无需额外拼接图表即可实现两个图例分别定位:
library(ggplot2) library(ggh4x) setwd("F:/Mutations/Graph_input") d <- read.csv(file = "ORF7b.csv", sep = ",", header = TRUE) p1 <- ggplot(d, aes(x= Position,y= Wild_Score)) + xlab("Positions") + ylab("Scores") + stat_difference(aes(ymin = 1, ymax = Wild_Score), alpha = 0.5, levels = c("Antigenic", "Non antigenic", "Neutral")) + scale_fill_discrete(name = "Regions") + geom_line(aes(y=1)) + geom_line(aes(y = A15S_Score), color = "blue", linewidth = 1) + geom_point(aes(x= 15, y = 1.194, color = "A15S"), size = 3) + scale_color_manual(name = "Mutations", values = c("A15S" = "blue")) + ggtitle("ORF7b protein") + theme(plot.title = element_text(hjust = 0.5)) + # 分别为两个图例设置独立位置 guides( color = guide_legend(position = c(0.92, 0.8)), fill = guide_legend(position = "bottom") ) p1
方案2:修正原有plot_grid拼接方案
如果你使用的ggplot版本较低,不支持单图例独立位置设置,仅需修改提取图例的代码,关闭fill图例的提取即可:
# 提取图例时仅保留color对应的Mutations图例,关闭fill的Regions图例 guide_color <- get_legend(p1 + guides(fill = "none")) # 主图关闭color图例,保留fill图例放在底部 plot_grid(p1 + guides(color = "none") + theme(legend.position = "bottom"), guide_color, ncol = 2, rel_widths = c(.9, .1))
内容的提问来源于stack exchange,提问作者Shatila Shahi
相关产品推荐
相关产品推荐

