在R中用ggplot2区分多个图例的位置
Posted
技术标签:
【中文标题】在R中用ggplot2区分多个图例的位置【英文标题】:differentiating positions of multiple legends with ggplot2 in R 【发布时间】:2021-10-21 11:56:30 【问题描述】:通过我的数据集,出现了两个传说。一个是 scale_color_manual(名为“Mutations”),另一个是 stat_difference(名为“Regions”)。我想把图例“Regions”放在底部,把图例“Mutations”放在右上角。 “Mutations”没问题,但我没有成功将“Regions”移到底部。我该怎么做? 这是我的示例数据集:
Position Wild_Score A15S_Score
4 1.07 1.07
5 1.076 1.076
6 1.067 1.067
7 1.112 1.112
8 1.112 1.112
9 1.169 1.169
10 1.146 1.146
11 1.16 1.16
12 1.188 1.181
13 1.188 1.181
14 1.201 1.194
15 1.201 1.194
16 1.155 1.148
这是我的代码:
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(d,aes(y = A15S_Score), color = "blue", size = 1) + theme(legend.position = c(0.92,0.8)) +
geom_point(d = d[,c(1,3)], aes(x= 15, y = 1.194, color = "A15S"), size = 3) + scale_color_manual(name = "Mutations", values = "A15S" = "blue") +
ggtitle("ORF7b protein") + theme(plot.title = element_text(hjust = 0.5))
我尝试了以下两行代码。
guide_color <- get_legend(p1 + guides(value = "none"))
plot_grid(p1 + guides(color = "none") + theme(legend.position = "bottom"), guide_color, ncol = 2, rel_widths = c(.9, .01))
我的图表现在有两个“区域”图例。右侧的一个与“突变”传说一起。一个在底部,如下所示。 duplicate legend 如何从右侧删除这个重复的图例?
【问题讨论】:
可能重复:***.com/q/68369581/12993861 我更新了我的帖子。你能检查我哪里做错了吗? 【参考方案1】:做这样的 hack 总是很麻烦。但也许这就是你要找的:
library(ggplot2)
library(ggh4x)
library(cowplot)
p1 <- ggplot(d, aes(Position, Wild_Score)) +
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(data = d, aes(y = A15S_Score), color = "blue", size = 1) +
geom_point(data = d[, c(1, 3)], aes(x = 15, y = 1.194, color = "A15S"), size = 3) +
scale_color_manual(name = "Mutations", values = c("A15S" = "blue")) +
labs(title = "ORF7b protein", x = "Positions", y = "Scores") +
theme(plot.title = element_text(hjust = 0.5))
guide_fill <- get_legend(p1 + guides(color = "none") + theme(legend.position = "bottom"))
plot_grid(p1 +
guides(fill = "none") +
theme(legend.position = c(0.92, 0.8)),
guide_fill, nrow = 2, rel_heights = c(10, 1))
数据
d <- structure(list(Position = 4:16, Wild_Score = c(1.07, 1.076, 1.067,
1.112, 1.112, 1.169, 1.146, 1.16, 1.188, 1.188, 1.201, 1.201,
1.155), A15S_Score = c(1.07, 1.076, 1.067, 1.112, 1.112, 1.169,
1.146, 1.16, 1.181, 1.181, 1.194, 1.194, 1.148)), class = "data.frame", row.names = c(NA,
-13L))
【讨论】:
以上是关于在R中用ggplot2区分多个图例的位置的主要内容,如果未能解决你的问题,请参考以下文章
R语言ggplot2可视化:在ggplot2中将图例(legend)移到图内自定义图例所处的位置自定义图例背景图例所处边框的颜色
R语言ggplot2可视化:ggplot2可视化将图像的图例(legend)移动到图像内部自定义图例所处的位置