jascha
jascha

Reputation: 55

Add straight line and text on a hexbinplot

I want to add a standard 1:1 line (with intercept 0 and slope 1) and some text (for example R-square) on my hexbinplot. The trial codes could be something like

require(hexbin)
x1 <- rnorm(10000)
x2 <- rnorm(10000)
df <- data.frame(cbind(x1, x2))
hex <- hexbin(x1, x2, xbins = 300)
hexbinplot(x2 ~ x1, data = df, aspect = '1', xbins = 300, xlim = c(-5, 5), ylim = c(-5, 5))
hexVP.abline(hexViewport(hex), 0, 1)

This gives me the plot below enter image description here

The line added have two issues which are

  1. It should be from the lower left corner to the top right corner,but the slope (should be 1) and intercept (should be 0) looks change when I zoom in/out the graphic window in RStudio and
  2. the both ends of the line does not extend to the plot border

Another question is about how to add a text on the plot.

The ideal plot could be looks like enter image description here

Upvotes: 3

Views: 704

Answers (1)

Roland
Roland

Reputation: 132969

Cute that a package still uses lattice for graphics. That's really retro!

Here is the lattice way:

hexbinplot(x2 ~ x1, data = df, aspect = '1', xbins = 300, xlim = c(-5, 5), ylim = c(-5, 5), 
           panel = function(x, y, ...) {
             panel.hexbinplot(x, y, ...)
             lattice::panel.abline(a = 0, b = 1)
           })

resulting plot

(Edit: After you added additional requirements: Use panel.text to add text to a lattice plot.)

Personally, I'd use ggplot2 and its geom_hex:

library(ggplot2)
ggplot(df, aes(x = x1, y = x2)) +
  geom_hex(bins = 300) +
  xlim(-5, 5) + ylim(-5, 5) +
  geom_abline(intercept = 0, slope = 1)

Upvotes: 4

Related Questions