我有一个包含多个面板的格子条形图,我想将每个条形的总和添加到这些条形的顶部(例如,(70)在左上角的第一个条形的顶部,第二个(20),上的第三个,依此类推)。这里有一个类似的question,但是我找不到一种适合我的绘图的方法。与该示例不同,我想做的是在每个竖条的顶部加上男性和女性的“总和”。我也无法使用(150)分别标记它们,如here所示。使用ltext或其他任何方式的任何建议都将非常有帮助。civ1<-c("Single","Single","Marr","Marr","Single","Single","Marr","Marr","Single","Single","Marr","Marr","Single","Single","Marr","Marr")Sex<-rep(c("women","men"),8)Year<-rep(c(rep(1990,4),rep(2000,4)),2)Type1<-c(rep("Traditional",8),rep("Dual-earner",8))Earn1<-c(seq(10, 160, by = 10))df<-as.data.frame(cbind(civ1,Sex,Year,Type1,Earn1))df$Earn1<-as.numeric(levels(df$Earn1))[df$Earn1]my.key<-list(space="bottom",text=list(c("Women","Men"),col=c("black","black")), columns=2,points=T,pch=15,col=c("darkgray","lightgray"),cex=0.8)labels=c("70","20","150","110")print(figure1<-barchart(Earn1~civ1|Year+Type1,df,groups=Sex, ylim=c(0,350),horizontal=F,col=c("darkgray","lightgray"),cex=0.8,ylab="Earnings",stack=T,layout=c(2,2),key=my.key,par.settings = list(strip.background=list(col=c("white","lightyellow")),panel=function(x,y,subscripts...){ panel.grid(h=-1,v=0) panel.barchart(...) ltext(1,200, labels[subscripts]) #not working! }))) (adsbygoogle = window.adsbygoogle || []).push({}); 最佳答案 我看到几个问题。首先,您的panel=参数位于par.settings参数内部,这是不正确的。它应该直接传递到barchart。然后,由于缺少逗号,您遇到了一些语法问题,而且我不确定您的标签仅适用于4个值的方式。无论如何,以下代码应该可以工作。barchart( Earn1~civ1|Year+Type1,df, groups=Sex, ylim=c(0,350), cex=0.8, ylab="Earnings", horizontal=F, stack=T, layout=c(2,2), col=c("darkgray","lightgray"), key=my.key, par.settings = list(strip.background=list(col=c("white","lightyellow"))), panel=function(x,y,subscripts,...){ panel.grid(h=-1,v=0) panel.barchart(x,y,subscripts=subscripts,...) t <- aggregate(y~x, data.frame(x,y), FUN=sum) panel.text(t$x,t$y, labels=t$y, pos=3) })除了解决上述问题外,我还使用aggregate()计算每一列的总数,并使用这些值在适当的位置绘制文本标签。结果图如下 (adsbygoogle = window.adsbygoogle || []).push({});
10-07 18:29