简体   繁体   English

R-在带有多个条形图的条形图中间添加标签

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

I try to draw plot with several rows of bars using barplot . 我尝试使用barplot绘制带有多排条形图的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. 但是,据我所知,并不是所有的标签都会出现,因为它们的宽度太大(可能会重叠),并且plot会掉落它们。 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. 如果我使用axis cex.axis属性使字体变小,则与其他元素和丑陋的字体相比,它会成比例地变小。

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. 我已经尝试过解决该问题的解决方案,例如将xaxt="n"添加到barplot ,设置las=2axis(1, at=1:4, cex.axis=1, labels=b, tck=0) ,设置names.arg中的barplot ,但无济于事。

It was almost there: need to exchange axis command with these two commands: 快要到了:需要用以下两个命令交换axis命令:

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. barplot被迫生成太多标签,无法将它们放置在一条水平线上。

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. 因此,仅剪切所需的中心标签位置( bplot第二行)并粘贴标签。

barplot解析

If you wanna X axis to cross Y axis, you can make it longer by adding the invisible label: 如果要使X轴与Y轴交叉,可以通过添加不可见标签来使其更长:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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