Rotate whole ggplot, keep legend unrotated

This is the best I could do:

library(ggplot2)
#> Warning: package 'ggplot2' was built under R version 4.1.2
library(grid)
library(cowplot)
library(ggplotify)
#> Warning: package 'ggplotify' was built under R version 4.1.2

p <- ggplot(mtcars, aes(mpg, color = factor(cyl))) + 
  geom_density()


rotation <- 45

leg <- as.grob( ~ plot(get_legend(p + theme_void())))

p_rot <- p + theme(legend.position = "none",
                   axis.title.y = element_text(angle = -90)) + 
  annotation_custom(textGrob("This is a title!", rot = -rotation,
                             x = unit(1.1, "npc"), y = unit(1.1, "npc"))) + 
  annotation_custom(textGrob("This is a caption", rot = -rotation,
                             x = unit(-0.1, "npc"), y = unit(-0.1, "npc")))

grid.newpage()
vp <- viewport(name = "rotate", angle = rotation, width = 0.5, height = 0.5)
pushViewport(vp)
print(p_rot, vp = "rotate", newpage = FALSE)
#> Warning in grid.Call.graphics(C_setviewport, vp, TRUE): cannot clip to rotated
#> viewport
#> Warning in grid.Call.graphics(C_setviewport, vp, TRUE): cannot clip to rotated
#> viewport
vp = viewport(x=0.15, y=0.8, width=0, height=0)
pushViewport(vp)
grid.draw(leg)

Created on 2022-02-07 by the reprex package (v2.0.1)

1 Like