3

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 :)

Dani Depi
  • 313
  • 3
  • 16

3 Answers3

7

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

user20650
  • 24,654
  • 5
  • 56
  • 91
  • Hi how long. Me again... You know how do this using just the command 'hexbinplot'? Now I need to be with this command. I tried everything and failed. – Dani Depi Jan 20 '16 at 15:11
  • Hi Dani; im not really a lattice user so im not sure. I would think there is a way to use the panel argument so might be worth asking a new question ... but another (slightly easier) workaround is `hexbinplot(y~x) + xyplot(z~w, col="red", pch=16, cex=2)` – user20650 Jan 20 '16 at 19:12
2

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' )
enterenter
  • 88
  • 1
  • 5
2

Try this... it should work fine. Just create a panel.function within your hexbinplot function:

hexbinplot(d.frame$X ~ d.frame$Y
   ,aspect=...,cex.title=...
   ,panel=function(x, y, ...){
      panel.hexbinplot(x,y,...)
   #   panel.curve(...)        # optional stuff
   #   panel.text(...)         # optional stuff
      panel.points(x=c(25,50),y=c(100,150),pch=20,cex=3.2)
   }
)

take a look for instance at: How to add points to multi-panel Lattice graphics bwplot?

Community
  • 1
  • 1
Manuel F
  • 145
  • 2
  • 7