Preserving proportions in the R grid

To draw a "crossed" rectangle 2 times its width, using the low-level graphics packages that I call:

 xlim <- c(0, 500) ylim <- c(0, 1000) plot.new() plot.window(xlim, ylim, asp=1) rect(xlim[1], ylim[1], xlim[2], ylim[2]) lines(c(xlim[1], xlim[2]), c(ylim[1], ylim[2])) lines(c(xlim[1], xlim[2]), c(ylim[2], ylim[1])) 

The drawing has a nice feature: the aspect ratio is preserved, so if I change the size of the chart window, I get the same proportions between the width and the width.

How to get an equivalent result with grid graphics?

+7
r plot r-grid
source share
2 answers

You must create a viewport that uses square normalized parent coordinates, see ?unit :

"snpc" : (...) This is useful for creating things that are proportions of the viewport but should be square (or have a fixed aspect ratio).

Here is the code:

 library('grid') xlim <- c(0, 500) ylim <- c(0, 1000) grid.newpage() # like plot.new() pushViewport(viewport( # like plot.window() x=0.5, y=0.5, # a centered viewport width=unit(min(1,diff(xlim)/diff(ylim)), "snpc"), # aspect ratio preserved height=unit(min(1,diff(ylim)/diff(xlim)), "snpc"), xscale=xlim, # cf. xlim yscale=ylim # cf. ylim )) # some drawings: grid.rect(xlim[1], ylim[1], xlim[2], ylim[2], just=c(0, 0), default.units="native") grid.lines(xlim, ylim, default.units="native") grid.lines(xlim, rev(ylim), default.units="native") 

The default.units argument, for example. grid.rect forces the plotting functions to use the built-in coordinates ( xscale / yscale ). just=c(0, 0) indicates that xlim[1], ylim[1] denotes the bottom left node of the rectangle.

+3
source share

In ggplot2 (which is grid ) you can fix the aspect ratio using coord_fixed() :

 library(ggplot2) ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point() + coord_fixed(ratio = 0.5) 

This will fix the coefficient, and the ratio will be constant even if you change the size of the graphics window.

I am not sure if this is useful since you asked for a low-level grid solution. But I thought it might be useful, nonetheless.

+1
source share

All Articles