RedGreenBlue
RedGreenBlue

Reputation: 11

Displaying the number of counts per bin in a ggplot2 hexbin graph

I'm working on a project to simulate the movement of missing ships. I've made a distribution map using this code:

library("ggplot2")

a <- rnorm(1000, 30.2, 2)
b <- rnorm(1000, 10, 5)
y <- (x + a + b) * 0.6

df <- data.frame(x,y)
p <- ggplot(df,aes(x=x,y=y)) +  
  ggtitle("A Priori Map") + xlab("Longtitude") + ylab("Latitude") +
  scale_fill_gradientn(colors = topo.colors(10))

p + stat_binhex(show.legend = T, bins = 20)

This produces a map like this:

A hexbin map

However, instead of showing the number of counts using a color, I would like to show the actual count in a point. So if the program 'landed' on a certain point 3 times, it would display '3'.

How can this be done in R?

Upvotes: 1

Views: 566

Answers (1)

eipi10
eipi10

Reputation: 93811

Here's how to add counts to the existing graph:

library(ggplot2)
theme_set(theme_bw())

set.seed(2)
a <- rnorm(1000, 30.2, 2)
b <- rnorm(1000, 10, 5)
x = rnorm(1000)
y <- (x + a + b) * 0.6

df <- data.frame(x,y)

p <- ggplot(df,aes(x=x,y=y)) +  
  ggtitle("A Priori Map") + 
  xlab("Longtitude") + ylab("Latitude") +
  scale_fill_gradientn(colors = topo.colors(10)) +
  stat_binhex(show.legend = T, bins = 20)

p + geom_text(stat="binhex", bins=20, aes(label=..count..), show.legend=FALSE,
              colour=hcl(15,100,60), fontface="bold", size=3.5)

enter image description here

To remove the fill colours, you could do:

ggplot(df,aes(x=x,y=y)) +  
  ggtitle("A Priori Map") + 
  xlab("Longtitude") + ylab("Latitude") +
  stat_binhex(bins = 20, fill=NA, colour="black") + 
  geom_text(stat="binhex", bins=20, aes(label=..count..), colour="red")

enter image description here

You could also use text size to highlight the regions of highest density:

ggplot(df,aes(x=x,y=y)) +  
  ggtitle("A Priori Map") + 
  xlab("Longtitude") + ylab("Latitude") +
  stat_binhex(show.legend = T, bins = 20, fill=NA, colour="grey70") + 
  geom_text(stat="binhex", bins=20, aes(label=..count.., size=..count..), colour="red") +
  scale_size_continuous(range=c(3,6)) +
  guides(size=FALSE)

enter image description here

Which also works without the hex-grid:

ggplot(df,aes(x=x,y=y)) +  
  ggtitle("A Priori Map") + 
  xlab("Longtitude") + ylab("Latitude") +
  geom_text(stat="binhex", bins=20, aes(label=..count.., size=..count..), colour="red") +
  scale_size_continuous(range=c(3,6)) +
  guides(size=FALSE)

enter image description here

Upvotes: 5

Related Questions