I am trying to edit text outside a plot, below the legend. I’ve followed the instructions suggested here and I’ve been able to put together the following code
p <- ggplot(Amh2, aes(x=syllable, y=durZ, color=condition)) +
geom_boxplot(lwd=1) +
theme_minimal() +
theme(text = element_text(size=15, family="Times New Roman")) +
theme(axis.text = element_text(size=13)) +
xlab("syllable") +
ylab("SDs from by-speaker mean") +
scale_y_continuous(breaks=scales::pretty_breaks(n=7), limits=c(-3,3)) +
theme(axis.title.x = element_text(margin=margin(t=5, r=0, b=0, l=0))) +
theme(axis.title.y = element_text(margin=margin(t=0, r=5, b=0, l=0))) +
theme(axis.text.x = element_text(color="#000000", size=12, family="Arial")) +
theme(axis.text.y = element_text(color="#000000", size=12, family="Arial")) +
theme(legend.position="right",
legend.justification="center",
legend.margin=margin(0,0,0,0),
legend.box.margin=margin(0,0,0,-5)) +
scale_color_manual(values=c("#FF0000", "#000000"), labels=c("focus", "nonfocus")) +
theme(legend.text = element_markdown(size=12, family="Arial")) +
theme(legend.title=element_blank()) +
annotate(geom="text", x=1, y=2.35, label="*", color="black", size=15) +
annotate(geom="text", x=2, y=2.35, label="*", color="black", size=15) +
annotate(geom="text", x=3, y=2.35, label="*", color="black", size=15) +
theme(legend.position="right", plot.margin = unit(c(1,1,3,1),"lines")) +
annotation_custom(grob = textGrob("A1-CV.CV"),
xmin = 2, xmax = 12.5, ymin = -4.5, ymax = 3.2) +
annotation_custom(grob = textGrob("B1-CV.CVC"),
xmin = 2, xmax = 12.65, ymin = -4.5, ymax = 2.7) +
annotation_custom(grob = textGrob("C1-CV.CVG"),
xmin = 2, xmax = 12.65, ymin = -4.5, ymax = 2.2)
gt <- ggplot_gtable(ggplot_build(p))
gt$layout$clip[gt$layout$name=="panel"] <- "off"
grid.draw(gt)
Here is the plot it produces, with the “A1, B1, C1” text added beneath the legend. (What I’m trying to do is add text to further expand on the x-axis labels.)
I have three questions from this, which I can’t seem to figure out.
-
Is there a way to add a text box below the legend, such that I could have multiple lines of text that are left-aligned? As it is, I’ve meticulously aligned the three annotations by adjusting their ymax and xmax, but it’s not ideal. Wrapping the text might also work, but it would be most ideal to control when it hops to the next line.
-
Is there a way to add selective bolding these annotations? This post explains how to do it with regular
annotate
, but I can’t figure out how to do it withannotation(custom)
. I would like the first label, for instance, to be “A1-CV.CV”. -
Is there a way to save the whole plot, using something like
ggsave
? I want to save the plot with no loss in quality, but it seems likeggsave
doesn’t pick up the added custom annotations – it just saves the base plot.