ggplot2 remove legend removes annotations

TibialCuriosity

I am creating a plot with a 2nd y axis to note categories of fitness. I've gotten the categories and labels using hline and annotate. I have specified a fill to the box plot which produces a legend. This legend than covers the annotations, but removing the legend also removes all annotation. Is there a way to remove only the annotation. See code below:

Without legend:

fmsft <- ggplot(Fboxm, aes(test, count))

fmsft + geom_boxplot(aes(fill = test), show.legend = FALSE) + 
  labs(x="Test", y=expression("Estimated VO"["2Max"])) + 
  geom_hline(yintercept = 23.9, size = 1.3) + 
  annotate("text", label = "Very Poor",
           x = 7, y = 23.9) +
  coord_cartesian(xlim = c(0,6), clip = "off") +
  geom_hline(yintercept = 28.6, size = 1.3) + 
  annotate("text", label = "Poor",
           x = 7, y = 28.6) +
  geom_hline(yintercept = 34.6, size = 1.3) + 
  annotate("text", label = "Fair",
           x = 7, y = 34.6) +
  geom_hline(yintercept = 40.6, size = 1.3) + 
  annotate("text", label = "Good",
           x = 7, y = 40.6) +
  geom_hline(yintercept = 46.5, size = 1.3) + 
  annotate("text", label = "Excellent",
           x = 7, y = 46.5) +
  geom_hline(yintercept = 56, size = 1.3) +
  annotate("text", label = "Superior",
         x = 7, y = 56)

Nolegend

With legend:

fmsft <- ggplot(Fboxm, aes(test, count))

fmsft + geom_boxplot(aes(fill = test)) + 
  labs(x="Test", y=expression("Estimated VO"["2Max"])) + 
  geom_hline(yintercept = 23.9, size = 1.3) + 
  annotate("text", label = "Very Poor",
           x = 7, y = 23.9) +
  coord_cartesian(xlim = c(0,6), clip = "off") +
  geom_hline(yintercept = 28.6, size = 1.3) + 
  annotate("text", label = "Poor",
           x = 7, y = 28.6) +
  geom_hline(yintercept = 34.6, size = 1.3) + 
  annotate("text", label = "Fair",
           x = 7, y = 34.6) +
  geom_hline(yintercept = 40.6, size = 1.3) + 
  annotate("text", label = "Good",
           x = 7, y = 40.6) +
  geom_hline(yintercept = 46.5, size = 1.3) + 
  annotate("text", label = "Excellent",
           x = 7, y = 46.5) +
  geom_hline(yintercept = 56, size = 1.3) +
  annotate("text", label = "Superior",
         x = 7, y = 56) 

legend

Thanks in advance!

r2evans

Add theme(plot.margin = unit(..., "cm")) to adjust the right margin.

Demonstration using mtcars.

library(ggplot2)
gg <- ggplot(mtcars, aes(disp, mpg)) +
  geom_point() +
  coord_cartesian(xlim = c(0, 480), clip = "off") +
  annotate("text", label = "quuxbar", x = 540, y = 20)
gg

enter image description here

gg + theme(plot.margin = unit(c(0.2, 2, 0.2, 0.2), "cm"))

enter image description here

FYI, the defaults:

theme_get()$plot.margin
# [1] 5.5points 5.5points 5.5points 5.5points

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related