英文:
patchwork: align tags inside panels for side-by-side plots
问题
需要在每个面板中以相同的相对位置获取"A"和"B"标签。
library(devtools)
library(ggplot2)
library(patchwork)
d1 <- runif(500)
d2 <- rep(c("Treatment","Control"), each=250)
d3 <- rbeta(500, shape1=100, shape2=3)
d4 <- d3 + rnorm(500, mean=0, sd=0.1)
plotData <- data.frame(d1, d2, d3, d4)
p2 <- ggplot(data=plotData) + geom_boxplot(aes(x=d2, y=d1, fill=d2)) + theme(legend.position = "right")
((p2 + p2) &
theme(legend.position = "right", plot.tag.position = c(.785, .96))) +
plot_annotation(tag_levels = "A") +
plot_layout(guides = "collect")
在这里的代码中,你可以看到"A"和"B"标签的相对位置在每个面板中是相同的。
英文:
I need the "A" and "B" tags at the same relative position in each panel.
library(devtools)
library(ggplot2)
library(patchwork)
d1 <- runif(500)
d2 <- rep(c("Treatment","Control"),each=250)
d3 <- rbeta(500,shape1=100,shape2=3)
d4 <- d3 + rnorm(500,mean=0,sd=0.1)
plotData <- data.frame(d1,d2,d3,d4)
str(plotData)
p2 <- ggplot(data=plotData) + geom_boxplot(aes(x=d2,y=d1,fill=d2)) + theme(legend.position = "right")
((p2 + p2) &
theme(legend.position = "right", plot.tag.position = c(.785, .96))) +
plot_annotation(tag_levels = "A") +
plot_layout(guides = "collect")
positioning as suggested here <https://stackoverflow.com/questions/69065003/using-patchwork-to-annotate-plots-that-have-labels-in-different-positions> returned one within-panel tag only.
I think the legend position is in the way of justifying the labels, as placing the plots in 1 column solved the problem. But, I need side-by-side and the mutual legend at the right. How do I change my code?
Thanks for stopping by.
答案1
得分: 2
以下是翻译好的部分:
问题出在这里,因为标签功能似乎根据每个图的位置提示来进行定位,而且由于一个图包含图例,它们会错位。我们可以通过使用 guide_area()
将图例提取到单独的区域来解决这个问题。
((p2 + p2 + guide_area()) &
theme(legend.position = "right", plot.tag.position = "topright")) +
# 如果你想要标签嵌入,plot.tag.position = c(.9, .96) 也看起来不错
plot_annotation(tag_levels = "A") +
plot_layout(guides = "collect", widths = c(2,2,1))
英文:
The trouble arises here because the tagging functionality seems to take its positioning cues from each plot, and since one plot includes the legend, these are misaligned. We can address this by extracting the legend into a separate area using guide_area()
.
((p2 + p2 + guide_area()) &
theme(legend.position = "right", plot.tag.position = "topright")) +
# plot.tag.position = c(.9, .96) looks good too if you want the tags inset
plot_annotation(tag_levels = "A") +
plot_layout(guides = "collect", widths = c(2,2,1))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论