R - Lattice Xyplot - How to Add Error Bars to Groups and Summary Lines

R - Lattice xyplot - How do you add error bars to groups and summary lines?

You could create your own panel function to plot a +/- SD region. For example

#new panel function
panel.se <- function(x, y, col.se=plot.line$col, alpha.se=.25, ...) {
plot.line <- trellis.par.get("plot.line")
xs <- if(is.factor(x)) {
factor(c(levels(x) , rev(levels(x))), levels=levels(x))
} else {
xx <- sort(unique(x))
c(xx, rev(xx))
}
means <- tapply(y,x, mean, na.rm=T)
vars <- tapply(y,x, var, na.rm=T)
Ns <- tapply(!is.na(y),x, sum)
ses <- sqrt(vars/Ns)
panel.polygon(xs, c(means+ses, rev(means-ses)), col=col.se, alpha=alpha.se)
}

and then you can use it like

#include new panel function
xyplot(CI~Time, groups=Name, data=df, ty=c("l", "p"),
panel = function(x, y, ...) {
panel.se(x,y, col.se="grey")
panel.xyplot(x, y, ...)
panel.linejoin(x, y, horizontal = FALSE,..., col="black", lty=1, lwd=4)

}
,xlab="Measurement Time Point",
ylab=expression("CI"~(l/min/m^"2")), main="Cardiac Index")

which results in

Sample Image

Add jittered data points to lattice xYplot with error bars

Use horizontal=FALSE:

panel.stripplot(d$Species, d$value,                                         
jitter.data = TRUE, cex=0.2,horizontal=FALSE, ...)

Internally is just a call to :

panel.xyplot(d$Species, d$value, cex=0.2,jitter.x=TRUE, ...)

Sample Image

Add standard deviation as grey smoothed bands to lattice xyplot

Its a tricky one with creating a gray smooth lines - your best bid is to play with panel.smoother from latticeExtra package, but it has a lot of weird parameters so its not easy to hack it out of box.

However, doing typical standard deviation bars from your data is easy with xYplot from Hmisc package.

First, you have to define lower and upper limits for your standard deviation bars based on your corresponding data. I just use your standard deviation symmetrically on both sides of the values, but you can divide it by two depending on how you calculated it:

data$MM_sd_hi <- data$MM+data$SD.MM  
data$MM_sd_low <- data$MM-data$SD.MM
data$KK_sd_hi <- data$KK+data$SD.KK
data$KK_sd_low <- data$KK-data$SD.KK

Than you add those limits within Cbind function inside xYplot. You need to increase your ylim a bit more to accommodate this, because xYplot does something weird with scales. Here is the code:

library(Hmisc)
library(gridExtra)
a <- xYplot(Cbind(MM, MM_sd_low, MM_sd_hi)~Period | Day, data=data, layout=c(6,1),
type="o", xlab="Period",ylab="Loads", ylab.right = "Loads",
main ="Daily trend", index.cond=list(c(5,6,4, 1:3)), ylim = c(0,170),
scales=list(x=list(at=seq(1,3,1),labels=c("B","F","A")),
y=(list(alternating=3))),
key = list(text = list("MM"), points = list(pch=1, col="steelblue2"),
text = list("KK"), points = list(pch=1, col="violet"),
text = list("d-KK = 306"), lines = list(lty=4, lwd=2, col="green4"),
text = list("u-KK = 312"), lines = list(lty=4, lwd=2, col="red"),
text = list("s-KK = 41"), lines = list(lty=4, lwd=2, col="gold"),
border = F)
)

b <- xYplot(Cbind(KK, KK_sd_low, KK_sd_hi)~Period|Day,data=data,layout=c(6,1),
type="o", col="violet", xlab="Period", ylab="Loads", ylab.right = "Loads",
index.cond=list(c(5,6,4, 1:3)), ylim = c(0,500),
scales=list(x=list(at=seq(1,3,1),labels=c("B","F","A")),
y=(list(alternating=3))),
panel = function(x,y,...) {
panel.abline(h=306,lty = 4, lwd=2, col="green4")
panel.abline(h = 312, lty = 4, lwd=2, col="red")
panel.abline(h = 41, lty = 4, lwd=2, col="gold")
panel.xYplot(x,y,...)
}
)
grid.arrange(a,b, nrow=2)

Sample Image

Adding error bars to a barchart with multiple groups

Here is another answer I was given using lattice.

prepanel=function(y, stderr, subscripts=subscripts, ...){
uy <- as.numeric(y+stderr[subscripts])
ly <- as.numeric(y-stderr[subscripts])
list(ylim=range(y,uy,ly, finite=TRUE))
}
panel.err=function(x, y, subscripts, groups, stderr, box.ratio, ...){
d <- 1/(nlevels(groups)+nlevels(groups)/box.ratio)
g <- (as.numeric(groups[subscripts])-1); g <- (g-median(g))*d
panel.arrows(as.numeric(x)+g,y-stderr[subscripts], as.numeric(x)+g, y+stderr[subscripts],
code=3,angle=90, length=0.025)
}
barchart(Change~fTreat,groups=Process,change,
stderr=change$stderr,
ylab="Pocertage change",
xlab="Treatment",
ylim=-115:50,
auto.key=list(points=FALSE,rectangles=TRUE,columns=2),
scales=list(alternating=FALSE,
tick.number=7,
tck=c(-1,0)),
prepanel=prepanel,
panel=function(x, y, subscripts, groups, stderr, box.ratio, ...){
panel.barchart(x, y, subscripts=subscripts,
groups=groups, box.ratio=box.ratio,origin=0, ...)
panel.abline(h=0,col="black",...)
panel.err(x, y, subscripts=subscripts,
groups=groups, box.ratio=box.ratio,stderr=change$stderr)
}
)

A big thank you to Walmes Marques Zeviani for providing the code

Here is the modified data:

change <- structure(list(Treat = structure(c(3L, 4L, 1L, 2L, 3L, 4L, 1L, 
2L), .Label = c("12-380", "12-750", "8-380", "8-750"), class = "factor"),
Process = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L), .Label = c("Respiration",
"Calcification"), class = c("ordered", "factor")), Change = c(-33L,
-35L, 21L, 18L, 7L, -29L, -8L, -79L), stderr = c(20L, 6L,
10L, 9L, 33L, 38L, 21L, 32L), fTreat = structure(c(1L, 2L,
3L, 4L, 1L, 2L, 3L, 4L), .Label = c("8-380", "8-750", "12-380",
"12-750"), class = c("ordered", "factor"))), .Names = c("Treat",
"Process", "Change", "stderr", "fTreat"), row.names = c(NA, -8L
), class = "data.frame")

rotating the grid to plot horizontal errors bars with Hmisc::xYplot in R

You have to directly call print on lattice object (it's mentioned in grid documentation RShowDoc("grid", package="grid") - "Adding lattice to grid"):

require(grid)
grid.newpage()
pushViewport(viewport(angle = 90, name = "VP"))

print(
xYplot(Cbind(coefi,lower, upper)~x, data=estimate, , varwidth = TRUE,
ylab="Betas", xlab="Inclinaçao das Covariáveis com respectivos 95% intervalos de credibilidade \n N=409",
ylim=with(estimate,c(min(lower)-.5, max(upper)+.5)),
scales=list(cex=1.2, x = list(at=seq(1,16,by=1), labels = legenda)),
abline=c(list(h=0), lty="dotted", col= "grey69"),
xlab.top="Adesao ao Tratado de Cooperaçao de Patentes, 1970-2000",
draw.in = "VP"
),
newpage=FALSE
)

Rotated xYplot

Lattice xyplot - Matrix used to divide groups into subplots

See the layout= parameter on the ?xyplot help page.It allows you to specify the number of columns and rows you would like

xyplot(prop ~ indtegn_alder | salgskanal,
data=fewGrid2,type='smooth',span=0.20, lwd=2.5,
xlab="Alder", ylab="Sandsynlighed", ylim=c(0,0.5), group= first_kundetype,
layout=c(1,5))


Related Topics



Leave a reply



Submit