在lattice中,在有2个组时添加条形图的误差线

3

我知道使用ggplot2会更容易,但我需要使用lattice完成。

这是我的例子:

data <- structure(c(0.67, 0.67, 0.76, 0.66, 0.71, 0.6, 0.52, 0.6, 0.71, 0.76, 
0.76, 0.71, 0.6, 0.61, 0.9, 0.5, 0.58, 0.84, 0.68, 0.88,
0.89, 0.96, 1, 0.95, 1, 1, 0.98, 0.78, 0.98, 1, 
1, 0.99, 1, 1, 0.95, 0.92, 1, 0.91, 1, 0.87, 
0.91, 0.72, 0.73, 0.55, 0.82, 0.87, 0.64, 0.75, 0.75, 1, 
0.81, 0.79, 1, 0.74, 0.57, 0.84, 1, 0.95, 0.78, 0.95), .Dim = c(20L, 3L), 
.Dimnames =     list(
c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", 
"12", "13", "14", "15", "16", "17", "18", "19", "20"), c("A", 
"B", "C")))

means <- apply(data, 2, mean)

errors <- apply(data, 2, sd)

plot.data <- data.frame(colnames(data), means, errors)

colnames(plot.data) <- c("var", "mean", "error")

plot.data<-cbind(rbind(plot.data,plot.data),p=c(rep('n',3),rep('m',3)))
plot.data<-cbind(rbind(plot.data,plot.data),mb=c(rep('j',6),rep('k',6)))

绘图
library(lattice)
library(latticeExtra)
prepanel.ci <- function(x, y, lx, ux, subscripts,...) {
x <- as.numeric(x)
lx <- as.numeric(lx[subscripts])
ux <- as.numeric(ux[subscripts])
list(ylim = range(0, x, ux, lx, finite = TRUE))
}


panel.ci <- function(x, y, lx, ux, subscripts,...) {
x <- as.numeric(x)
y <- as.numeric(y)
lx <- as.numeric(lx[subscripts])
ux <- as.numeric(ux[subscripts])
panel.barchart(x, y, ...)
panel.arrows( x, lx, x, ux, col = 'black',
             length = 0.25, unit = "native",
             angle=90 ,code = 2)
}

p <- useOuterStrips(barchart(mean~var|p+mb, data=plot.data,stack=F,
          lx=plot.data$mean,
          ux=plot.data$mean+plot.data$error,
          panel=panel.ci,
          prepanel=prepanel.ci))
print(p)

然后我可以正确地添加误差线,如图1所示enter image description here

当我添加一个组因子g时。

plot.data<-cbind(rbind(plot.data,plot.data),g=c(rep('aa',12),rep('tt',12)))

p<-useOuterStrips(barchart(mean~var|p+mb, group=g, plot.data))

print(p)

enter image description here

现在我添加了误差条,但出了问题:

p <- useOuterStrips(barchart(mean~var|p+mb, group=g, data=plot.data,stack=F,
          lx=plot.data$mean,
          ux=plot.data$mean+plot.data$error,
          panel=panel.ci,
          prepanel=prepanel.ci))
print(p)

有什么想法吗?

enter image description here


请查看以下链接:https://dev59.com/jWPVa4cB1Zd3GeqP4Ukb - user36102
1个回答

1
这是使用ggplot2的解决方案:
dodge <- position_dodge(width=0.9)
p <- ggplot(data=plot.data, aes(y=mean, x=var, fill=g)) +
  geom_bar(position=dodge, stat="identity") + facet_grid(mb ~ p)
p + geom_errorbar(aes(ymin=mean-error, ymax=mean+error), position=dodge, width=0.25)

这将产生:

enter image description here


谢谢您的回复。但我需要通过格子获得结果。 - user36102

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