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 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.
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))