首页 文章

如何合并R中的条形图中的列标签(堆叠条形图)?

提问于
浏览
1

我在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(数据),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英寸,总共有八个标签 . 我怎样才能做出这个改变?

非常感谢!

1 回答

  • 2

    如果您只希望在每个组下面都有居中标签,您可以执行以下操作:

    # 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)
    

    enter image description here

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

相关问题