Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

panel.text xyplot R

Tags:

r

lattice

I am adding text to different panels of a xyplot in lattice and was wondering if anyone knows a way to not specify a x and y coordinates or is there something similar to legend where you can say upper left or upper right,etc?

I ask because I want to use scales=free in the plotting code, but when I do the text in the mytext code ends up covering up parts of the graph and doesn't make for a good plot. I would like to have a way to plot the graphs without making individual plots because in my real dataset I have up to 10 grouping factor levels (sams in the code). The example provided is not as extreme as the real data.

Example data

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),]

Plot with scales=same. mytext x and y coordinates are specified.

    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)

Same thing with scales=free. Text is in odd places because all text has the same coordinates.

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)

Thanks for any help.

like image 969
user41509 Avatar asked Feb 25 '26 12:02

user41509


1 Answers

You can use grid.text() to specify units in a range-independent way. For example

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

With grid.text the x and y values use npc units by default which range from 0 to 1. So x=.5 means centered and y=.8 means 80% of the way to the top.

like image 168
MrFlick Avatar answered Feb 28 '26 05:02

MrFlick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!