Home > Mobile >  How do I change hexbin plot scales?
How do I change hexbin plot scales?

Time:04-29

How do I change hexbin plots scales?

I currently have this:

enter image description here

Instead of the scale jumping from 1 to 718, I would like it to go from 1 to 2, 3, 5, 10, 20, 40, 80, 160, 320, 640, 1280, 2560, 5120, 10240, 15935.

Here is the code I used to plot it:

hex <- hexbin(trial$pickup_longitude, trial$pickup_latitude, xbins=600)
plot(hex, colramp = colorRampPalette(LinOCS(12)))

CodePudding user response:

You cannot control the boundaries of the scale as closely as you want, but you can adjust it somewhat. First we need a reproducible example:

set.seed(42)
X <- rnorm(10000, 10, 3)
Y <- rnorm(10000, 10, 3)
XY.hex <- hexbin(X, Y)

To change the scale we need to specify a function to use on the counts and an inverse function to reverse the transformation. Now, three different scalings:

plot(XY.hex)    # Linear, default
plot(XY.hex, trans=sqrt, inv=function(x) x^2)  # Square root
plot(XY.hex, trans=log, inv=function(x) exp(x)) # Log

The top plot is the original scaling. The bottom left is the square root transform and the bottom right is the log transform. There are probably too many levels to read these plots clearly. Adding the argument colorcut=6 to the plot command would reduce the number of levels to 5.

Three Plots

CodePudding user response:

Here's a ggplot method, where you can specify whatever breaks you want.

library(ggplot2)
library(RColorBrewer)
##
#   made up sample
#
set.seed(42)
X    <- rgamma(10000, shape=1000, scale=1)
Y    <- rgamma(10000, shape=10,   scale=100)
dt   <- data.table(X, Y)
##
#   define breaks and labels for the legend
#
brks <- c(0, 1, 2, 5, 10, 20, 50, 100, Inf)
n.br <- length(brks)
labs <- c(paste('<', brks[2:(n.br-1)]), paste('>', brks[n.br-1]))
##
#
ggplot(dt, aes(X, Y)) geom_hex(aes(fill=cut(..count.., breaks=brks)), color='grey80') 
  scale_fill_manual(name='Count', values = rev(brewer.pal(8, 'Spectral')), labels=labs)
                

enter image description here

  • Related