简体   繁体   中英

R - add labels to the middle of barplot with multiple bars

I try to draw plot with several rows of bars using barplot .

x11()
X=c('May','July','September','November')
Y1=c(1,1,3,5)
Y2=c(5,5,6,7)
Y3=c(9,8,0,2)
C=rbind(Y1,Y2,Y3)
l <- c()
a=b=l
i <- 1
while(i<=length(X)) {
a[[i]] <- ''
b[[i]] <- X[i]
    i <- i + 1
}
l=rbind(a,b,a,a)
plot(0, xlim=c(1,(length(Y1)*4)), ylim=c(0,10), )
bplot<-barplot(C,xaxt="n",beside=T, xlim=c(1,(length(Y1)*4)), ylim=c(0,10), lty=1, las=1)
axis(1, at=1:(length(Y1)*4), cex.axis=1, labels=l, tck=0)
Sys.sleep(40)

条形图

But not all the labels appear, as I understood, as they are too large in width (could overlap) and plot drops them. I had to create additional void labels for those bars that should not have labels (left ones, right ones and gaps). If I made font smaller using axis cex.axis property, it becomes unproportionally small compared to oher elements and lloks ugly.

I've tried solutions from that question , like adding xaxt="n" to barplot , setting las=2 , axis(1, at=1:4, cex.axis=1, labels=b, tck=0) , set names.arg in barplot , but nothing helped.

It was almost there: need to exchange axis command with these two commands:

bplot=bplot[2,]
axis(1, at=bplot, cex.axis=1, labels=X, tck=0)

barplot was forced generarating too many labels to have them placed into one horizontal line.

bplot
     [,1] [,2] [,3] [,4]
[1,]  1.5  5.5  9.5 13.5
[2,]  2.5  6.5 10.5 14.5
[3,]  3.5  7.5 11.5 15.5

So, cut only desirable central labels positions (2nd row of bplot ) and apply the labels.

barplot解析

If you wanna X axis to cross Y axis, you can make it longer by adding the invisible label:

# those two commands two continue the Xaxis to the crossing with Y axis
bplot=cbind(-1,bplot)
b=cbind('',b)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM