R格:考虑到分组,将文本添加到x轴上的散点图中

问题描述 投票:0回答:1

我有一个数据集,其中两个组y的两个日期x的值为gp。另外,对于每个这些值,我都想在x轴上添加一个数字n。这是生成数据和图形的代码:

set.seed(1234)
data0 <- expand.grid(gp = c("A","B")
                  , x = 1:2
                  )
data0$y <- round(runif(4),2)
data0$n <- round(100*runif(4),0)
data0

#   gp x    y  n
# 1  A 1 0.11 86
# 2  B 1 0.62 64
# 3  A 2 0.61  1
# 4  B 2 0.62 23

xyplot(y ~ x | gp, data=data0
       , panel = function(...) {
           panel.xyplot(...)
           panel.text(1,0.1,86)
           panel.text(2,0.1,64)           
       }
       )

这是图形:

enter image description here

我希望正确的n位于x轴上,即:考虑到分组gpx,应在x轴上添加n。知道如何应对吗?

r scatter-plot lattice
1个回答
0
投票

您可以使用subscripts来跟踪面板功能中的每一行。

xyplot(y ~ x | gp, data=data0,#subscripts=TRUE,
       panel = function(x,y,subscripts,...) {
           panel.xyplot(x,y,...)
           panel.text(data0$x[subscripts],0.1,data0$n[subscripts])
       }
)

您可能想要调整放置文本的位置(y = 0.1,以避免几乎使数据过度绘制。

((编辑:注释掉了subscripts=TRUE,这在这里是不必要的。)

© www.soinside.com 2019 - 2024. All rights reserved.