繁体   English   中英

如何在R(堆叠式barplot)的barplot中合并列标签?

[英]How to merge column labels in barplot in R (a stacked barplot)?

我在R中的数据如下所示:

    1-12 1-12 1-15 1-15 1-20 1-20 2-6 2-6 3-1-1 3-1-1 3-1 3-1 3-2 3-2 3-3 3-3
N    0    0   14    0   17    0   9   0    27     0   9   0  13   0  33   0
P    0    0    0   12    0   12   0   5     0    13   0   6   0   0   0   9
F    0    0    0    0    0    0   0   2     0    14   0   0   0   6   0  20

通过dput(data),R中的结果为:

    structure(c(0L, 0L, 0L, 0L, 0L, 0L, 14L, 0L, 0L, 0L, 12L, 0L, 
17L, 0L, 0L, 0L, 12L, 0L, 9L, 0L, 0L, 0L, 5L, 2L, 27L, 0L, 0L, 
0L, 13L, 14L, 9L, 0L, 0L, 0L, 6L, 0L, 13L, 0L, 0L, 0L, 0L, 6L, 
33L, 0L, 0L, 0L, 9L, 20L), .Dim = c(3L, 16L), .Dimnames = list(
c("N", "P", "F"), c("1-12", "1-12", "1-15", "1-15", "1-20", 
"1-20", "2-6", "2-6", "3-1-1", "3-1-1", "3-1", "3-1", "3-2", 
"3-2", "3-3", "3-3")))

我的代码是:

barplot(data,space=c(1,0.25),legend=rownames(data),col=c('white','black','grey'),las=2)

它看起来像一个普通的条形图,每列的底部都有一个标签...

但是,x轴上的标签太多,我想将两列的名称合并为一个(因为它们具有相同的名称),即在前两列的中间,只有一个标签“底部为1-12英寸,因此总共有八个标签。 我该如何进行更改?

非常感谢!

如果您只想在每个组下放置居中标签,则可以执行以下操作:

# suppress the x-axis and save your original plot's bar locations
bp <- barplot(data,space=c(1,0.25),legend=rownames(data),
             col=c('white','black','grey'),las=2,
             xaxt="n")

# draw a new axis using these values
axis(1,at=rowMeans(matrix(bp,ncol=2,byrow=TRUE)),
     labels=unique(colnames(data)),lty=0)

在此处输入图片说明

当然可以忽略重叠的图例...可以通过在原始barplot调用中使用legend.args更好地放置它来legend.args

暂无
暂无

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

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