在六边形图上添加直线和文本

3

我想在我的六边形图上添加一个标准的1:1线(截距为0,斜率为1)和一些文本(例如R平方)。试用代码可能是这样的

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)

这给我下面的图表 enter image description here 添加的线有两个问题:
  1. 它应该从左下角到右上角,但是当我在RStudio中缩放图形窗口时,斜率(应为1)和截距(应为0)似乎发生了变化
  2. 线的两端未延伸到图表边界
另一个问题是如何在图表上添加文本。
理想的图表可能看起来像 enter image description here
1个回答

4

很可爱,一个软件包仍然使用格子图形。那真的很复古!

以下是格子图形的方法:

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

生成的图形

(编辑: 在您添加了其他要求后: 使用panel.text将文本添加到lattice绘图中。)

个人而言,我会使用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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接