label - R lattice barchart: How to write the total sum on each bar in multiple panels? -
i have lattice bar chart multiple panels , add sum of each bar on top of bars (e.g. (70)
on top of first bar on top left, (20)
on second one, (150)
on third 1 etc.).
there similar question here not find way adapt code plot. unlike in example, add 'total sum' of men , women on top of each bar vertical bar. not label them separately using ltext
shown here. suggestion, using ltext
or other way, helpful.
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, = 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! })))
i see several problems. first, panel=
parameter inside par.settings
parameter incorrect. should passed barchart
directly. have syntax problems missing comma , i'm not sure how labels intended work 4 values. anyway, following code should work.
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) } )
aside fixing problems described above, i've use aggregate()
calculate total each column , used values plot text labels @ appropriate spot. resulting plot below
Comments
Post a Comment