在hexbinplot上添加直线和文本

zha*_*eng 3 plot r

我想在我的hexbinplot上添加标准的1:1行(截距0和斜率1)和一些文本(例如R-square).试用代码可能是这样的

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)
Run Code Online (Sandbox Code Playgroud)

这给了我下面的情节 在此输入图像描述

添加的行有两个问题

  1. 它应该是从左下角到右上角,但当我放大/缩小RStudio中的图形窗口时,斜率(应为1)和截距(应为0)看起来会发生变化
  2. 线的两端不会延伸到绘图边框

另一个问题是如何在情节上添加文字.

理想情节可能看起来像 在此输入图像描述

Rol*_*and 5

可爱的一个包仍然使用晶格的图形.那真是复古!

这是格子方式:

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)
           })
Run Code Online (Sandbox Code Playgroud)

结果情节

(编辑:添加其他要求后:用于panel.text向格子图添加文本.)

就个人而言,我会使用ggplot2及其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)
Run Code Online (Sandbox Code Playgroud)