在堆叠格子条形图中显示值

时间:2010-07-10 20:16:32

标签: graphics r lattice

我想为每个部分显示100%条形的值。不幸的是我不知道该怎么做。图形应该是格子因为图例位置(我用ggplot2尝试过,但你不能在一行中显示图例)。我对任何建议或想法感到高兴。

library(lattice)
data(postdoc, package = "latticeExtra")
colnames(postdoc) <- c("Legendtext 1", "2", "3", "4", "5")
colorset <- simpleTheme(col = c(rgb(166,27,30,maxColorValue = 255),
                                rgb(192,80,77,maxColorValue = 255), 
                                rgb(24,65,83,maxColorValue = 255),
                                rgb(60,143,167,maxColorValue = 255),
                                rgb(130,184,208,maxColorValue = 255)),
                                border = "white")
pl <- barchart(prop.table(postdoc, margin = 1),
               par.settings = colorset,
               auto.key = list(columns = 5, space = "bottom",
                               cex = 0.8, size = 1.4, between = 0.2,
                               between.columns = 0.1, adj = 1))

1 个答案:

答案 0 :(得分:18)

这是使用自定义面板功能实现的:

library(lattice)
library(plyr)

data(postdoc, package="latticeExtra")
colnames(postdoc) <- c("Legendtext 1", "2", "3", "4", "5")
colors <- c(rgb(166,27,30,maxColorValue = 255),
            rgb(192,80,77,maxColorValue = 255),
            rgb(24,65,83,maxColorValue = 255),
            rgb(60,143,167,maxColorValue = 255),
            rgb(130,184,208,maxColorValue = 255))
colorset <- simpleTheme(col=colors,
                        border="white")

pl <- barchart(prop.table(postdoc, margin=1),
               par.settings=colorset,
               panel=function(...) {
                 panel.barchart(...) 
                 tmp <- list(...)
                 tmp <- data.frame(x=tmp$x, y=tmp$y)
                 # calculate positions of text labels
                 df <- ddply(tmp, .(y),
                             function(x) {
                               data.frame(x, pos=cumsum(x$x)-x$x/2)
                             })
                 panel.text(x=df$pos, y=df$y,
                            label=sprintf("%.02f", df$x),
                            cex=0.7)
               },
               auto.key=list(columns=5, space="bottom",
                             cex=0.8, size=1.4, adj=1,
                             between=0.2, between.colums=0.1))

lattice plot http://img819.imageshack.us/img819/894/panelbarchart.png