Rotate a R plot with dynamic plot area

69 views Asked by At

I'm trying to rotate a plot to be incorporated into a shiny application. I found how to rotate a plot. To get it right it seems you need to fiddle with the the height and width of the viewport making it not a solution for a dynamic environment where you don't known the height and width a priori.

My question now is how do I rotate my plot in such a way that it remains dynamic and responsive to plot area changes?

My example:

p <- ggplot2::qplot(1:10)

library(grid)
grid.newpage()
print(p, vp=viewport(0, 0, width = unit(0.5, "npc"), just = c('left', 'bottom')))
print(p, vp=viewport(0.5, 0, angle = 90, height = unit(0.8, "npc"), width = 0.55, just = c('left', 'top')))

Depending on how the plotting area is it looks good or bad:

Vertically elongated

Observed: missing half of the rotated plot

Expected:

Horizontally elongated

Observed: missing half of the rotated plot enter image description here Expected: enter image description here

Square like

Nicely how it should be - showing both plots: enter image description here

1

There are 1 answers

2
asd-tm On

Edited upon the OP's cpmment.

We need to dynamically check dimensions of the graphics device every time the graph is plotted.

library(grid)
grid.newpage()
dev.size(units = "px")

print(p, vp=viewport(0, 0, 
                     width = unit(dev.size(units = "in")[1]*0.45, "inches"), 
                     height = unit(dev.size(units = "in")[2]*0.975, "inches"),
                     just = c('left', 'bottom')))
print(p, vp=viewport(0.5, 0, angle = 90, 
                     height = unit(dev.size(units = "in")[1]*0.45, "inches"), 
                     width = unit(dev.size(units = "in")[2]*0.975, "inches"), 
                     just = c('left', 'top')))

Note it does not affect changing of the graph whenever you strech it in your rstudio device preview window but it does change the size every time you newly plot your graph.

enter image description here

enter image description here

enter image description here