Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2 stat_binhex(): keep bin radius while changing plot size

I'd like to a find a way to keep regular hexagons (all sides have equal length) when resizing hexbin plots in ggplot2 without manually adjusting the binwidth parameter.

To illustrate:

d <- ggplot(diamonds, aes(carat, price))+ 
  stat_binhex(colour="white")
try(ggsave(plot=d,filename=<some file>,height=6,width=8))

yields hexagons that at least look regular to the eye:ggplot2 stat_binhex plot1

And

try(ggsave(plot=d,filename=<some other file>,height=6,width=12))

yields irregular hexagons:ggplot2 stat_binhex plot2

The documentation describes the binwidth parameter (e.g. binwidth = c(1, 1000)) which specifies bin width. I'd like a function which, when given any plot size, returns the right binwidth settings to create regular hexagons.

like image 504
metasequoia Avatar asked Feb 19 '23 15:02

metasequoia


1 Answers

Your choices are to set coord_fixed with an appropriate ratio so that the plot will not stretch over the size of the graphics device

In this case 5/17000 would appear reasonable

d <- ggplot(diamonds, aes(carat, price))+ 
  stat_binhex(colour="white") + coord_fixed(ratio = 5/17000)

The other option is to create the binwidths and ratio of the coordinate dimensions with the ratio of device dimensions in mind.

Unless the coordinate ratio is fixed (as per my first example), you can't expect to stretch the same plot into a window that is 1.5 times wider, without the plot looking stretched.

so if you are stretching the width by a factor of 1.5, then decrease the binwidth in the x dimension by a factor 1.5

d <- ggplot(diamonds, aes(carat, price))+ 
   stat_binhex(colour="white",bin.widths = c((5/45),17000/30 ))
like image 99
mnel Avatar answered Feb 21 '23 16:02

mnel