【问题标题】:panel.text xyplot Rpanel.text xyplot R
【发布时间】:2015-08-10 18:27:00
【问题描述】:

我在 lattice 中向 xyplot 的不同面板添加文本,想知道是否有人知道不指定 x 和 y 坐标的方法,或者是否有类似于图例的内容,您可以说左上角或右上角等?

我问是因为我想在绘图代码中使用 scales=free,但是当我这样做时,mytext 代码中的文本最终会覆盖图形的某些部分,并且不会产生良好的绘图。我想有一种方法来绘制图表而不制作单独的图,因为在我的真实数据集中我有多达 10 个分组因子级别(代码中的 sams)。提供的示例并不像真实数据那样极端。

示例数据

d_exp<-data.frame(sams=c(rep("A",6),rep("B",6),rep("C",6)),
    gear=c(rep(1:2,9)),
    fraction=c(.12,.61,.23,.05,.13,.45,0.3,.5,.45,.20,.35,.10,.8,.60,.10,.01,.23,.03),
    interval=c(rep(c(0,10,20),6)))

d_exp<-d_exp[order(d_exp$sams,d_exp$gear,d_exp$interval),]

比例尺=相同。 mytext 指定 x 和 y 坐标。

    mytext<-c("N=3","N=35","N=6")

   panel.my <- function(...) {
    panel.superpose(col=c("red","blue"),lwd=1.5,...)
    panel.text(x=2.5,y=0.5,labels=mytext[panel.number()],cex=.8) 
}

xyplot(fraction~interval | sams, data=d_exp,groups=gear,type="l",
    scales=list(relation="same",y=list(alternating=1,cex=0.8),x=list(alternating=1,cex=.8,abbreviate=F)),
    strip = strip.custom(bg="white", strip.levels = T),drop.unused.levels=T,as.table=T,
    par.strip.text=list(cex=0.8),panel=panel.my)

与 scales=free 相同。文本位于奇怪的位置,因为所有文本都具有相同的坐标。

xyplot(fraction~interval | sams, data=d_exp,groups=gear,type="l",
    scales=list(relation="free",y=list(alternating=1,cex=0.8),x=list(alternating=1,cex=.8,abbreviate=F)),
    strip = strip.custom(bg="white", strip.levels = T),drop.unused.levels=T,as.table=T,
    par.strip.text=list(cex=0.8),panel=panel.my)

感谢您的帮助。

【问题讨论】:

    标签: r lattice


    【解决方案1】:

    您可以使用grid.text() 以与范围无关的方式指定单位。例如

    library(grid)
    panel.my <- function(...) {
        panel.superpose(col=c("red","blue"),lwd=1.5,...)
        grid.text(x=.5,y=.8,label=mytext[panel.number()]) 
    }
    

    对于grid.textxy 值默认使用npc 单位,范围从0 到1。所以x=.5 表示居中,y=.8 表示到达顶部的80%。

    【讨论】:

    • 我厌倦了安装网格包,但网格不适用于 R 版本 3.2.1。听起来它会起作用。谢谢。
    • @user41509 grid 是 Lattice 需要运行的默认包。您不需要单独安装它。只需运行 library(gid) 即可加载。
    猜你喜欢
    • 1970-01-01
    • 2016-08-02
    • 1970-01-01
    • 2014-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多