在条形图底部添加标签

时间:2012-05-30 17:19:57

标签: r graphics lattice

我对格子很陌生,所以对我来说这是一次试错。

似乎无法通过典型的r理解来定制格子图形。

我想在每个条形图下面添加类似count(percentage)的内容,当它完成时应该看起来像这样:

labelled bar chart

正如您所看到的,我的代码没有标记正确的条形图。并非所有这些都是错误的。第一个应该是20(0.1%)。

这是我的代码:

grp1<-rep("grp1",20)
grp2<-rep("grp2",40)
grp3<-rep("grp3",60)
grp4<-rep("grp4",80)
grp <- c(grp1,grp2,grp3,grp4)

barchart(grp,horizontal=F, 
    par.settings = list(
    plot.polygon = list(col = c("#1E4150","#28556E","#32698C","#3C7DAA")) ),
        panel = function(x, y, subscripts, ...){  
            X <- table(x)
            panel.barchart(x,y,...) 
            percentages <- paste(round(table(X)/length(X),2),"%",sep="")
            lab1 <- paste( "(",percentages, sep="")
            lab1 <- paste( lab1,")", sep="")
            abs <- table(X)
            panel.text(1,-3, label = paste(abs,lab1), cex=0.8)
        } 
) 

1 个答案:

答案 0 :(得分:4)

我想也许你想做更像这样的事情:

barchart(grp,horizontal=F, 
    par.settings = list(
    plot.polygon = list(col = c("#1E4150","#28556E","#32698C","#3C7DAA")) ),
        panel = function(x, y, subscripts, ...){  
            panel.barchart(x,y,...) 
            percentages <- paste(round(y/sum(y),2),"%",sep="")
            lab1 <- paste( "(",percentages,")", sep="")
            panel.text(x,-3, labels = paste(y,lab1), cex=0.8)
        } 
) 

enter image description here