Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to plot points on hexbin graph in R?

I have two sets of data that need to plot on the same graph. A set is very large (~ 10⁶) and I want to plot with hexbin, and the other set is very small (~ 10) and I want to plot the points. How do I plot points on the hexbin? The closer to success I got was this:

bin = hexbin(x, y)
plot(bin)
pushViewport(dataViewport(x, y))
grid.points(x, y)

I appreciate any help :)

like image 741
Dani Depi Avatar asked Sep 05 '26 15:09

Dani Depi


2 Answers

Assuming you are using the hexbin package...

library(hexbin)
library(grid)

# some data from the ?hexbin help
set.seed(101)
x <- rnorm(10000)
y <- rnorm(10000)
z <- w <- -3:3

# hexbin
bin <- hexbin(x, y)

# plot  - look at str(p)
p <- plot(bin)

# push plot viewport
pushHexport(p$plot.vp)

# add points
grid.points(z, w, pch=16, gp=gpar(col="red"))

upViewport()

enter image description here

like image 119
user20650 Avatar answered Sep 08 '26 05:09

user20650


You can use the ggplot package for that task, see the code below, just replace the data.frame used in the data parameter for geom_point with the one for the points you want to plot.

library(ggplot2)
library(hexbin)
ggplot(diamonds, aes(carat, price)) + stat_binhex() + geom_point(data = diamonds[c(1,10,100,1000), ], aes(carat, price), size=10, color = 'red' )
like image 21
enterenter Avatar answered Sep 08 '26 03:09

enterenter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!