Search code examples
rplotgraphicspixel

OS-independent way of making a plot window of a specific size in pixels?


It seems that this was possible in the past, but it looks like dev.new no longer has a unit argument. All that I am trying to do is make a new plotting window of size 320 x 240 px in such a way that the code will not be OS-dependent and plot a single pixel in that window. I considered using par's parameters (e.g. din, fin, and pin), but par's documentation suggests that the plotting functions merely take these as suggestions and dev.size's documentation suggests that din is OS-dependent. X11 might do the trick, but its arguments are all in inches. Do I really have to do all of my work in inches and then covert that to pixels? Or is there an easier way?


Solution

  • A little bit of a hack, but dev.size accepts units and so we can infer. We just for an instant open a display and get the size in both inches and pixel. We wrap it into a closure, so we can use it multiple times while just opening the device once.

    convertInToPx<-function() {
        dev.new()
        insize<-dev.size(units="in")
        pxsize<-dev.size(units="px")
        on.exit(dev.off())
        ratio<-insize/pxsize
        function(width, height, inverse = FALSE) {
            if (inverse)
                ratio<-1/ratio
            list(width = width*ratio[1], height = height*ratio[2])
        }
    }
    myconvert<-convertInToPx()
    #results on my laptop
    myconvert(320, 240)
    # $width
    # [1] 4.444444
    #
    # $height
    # [1] 3.333333
    myconvert(4.44444444444, 3.3333333, inverse=TRUE)
    # $width
    # [1] 320
    #
    # $height
    # [1] 240
    

    You can calculate the inches given the desired pixel size.