R barplot - 即使只有一个类别,也会显示图例

时间:2014-03-12 14:04:30

标签: r plot legend-properties

我正在使用R中的barplot()函数在堆叠条形表示下绘制来自同一绘图中的多个数据集的值,并且我注意到如果对于某个绘图我只有一个数据的数据,则不显示图例组。具有两个或更多类别(即数据集)不会引起任何问题并且图例正确显示。有没有想过是否可以强制它显示,即使只有一个类别?或者我必须添加一个虚拟类别,如果该绘图我只有一个数据集可用的数据。谢谢。

编辑:以下是我对条形图的调用方式:

barplot(bars, col = color_map[available_data], legend.text = T, 
        args.legend(bty = 'n'), ylim = my_computed_ylim, 
        xlim = my_computed_xlim, xlab = "X label", ylab = "Y label") 

a = rep(5,25) 
b = rep(10,25) 
bars = rbind(a,b) 
barplot(bars, col = seq(1,nrow(bars), by = 1), legend.text = T, 
        args.legend = c(bty = 'n')) bars = bars[-1,] barplot(bars, 
        col = 2, legend.text = T, args.legend = c(bty = 'n'))

1 个答案:

答案 0 :(得分:2)

当您键入bars = bars[-1,]时,会自动强制转换为矢量。为此,您应该转换回具有命名行的矩阵。

示例:

a = rep(5,25); 
b = rep(10,25); 
bars = rbind(a,b); 
barplot(bars, col = seq(1,nrow(bars), by = 1), legend.text = T, args.legend = c(bty = 'n')); 
bars = matrix(bars[-1,],nrow=1); rownames(bars)=c('b');  ### THIS IS DIFFERENT
barplot(bars, col = 2, legend.text = T, args.legend = c(bty = 'n'))

这有帮助吗?

修改

要真正看到两只野兽之间的区别,请看这个例子:

> a = rep(5,25); b = rep(10,25); bars = rbind(a,b); 
> bars
  [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14] [,15] [,16] [,17]
a    5    5    5    5    5    5    5    5    5     5     5     5     5     5     5     5     5
b   10   10   10   10   10   10   10   10   10    10    10    10    10    10    10    10    10
  [,18] [,19] [,20] [,21] [,22] [,23] [,24] [,25]
a     5     5     5     5     5     5     5     5
b    10    10    10    10    10    10    10    10


> bars.old = bars[-1,]
> bars.old
 [1] 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10


  length of 'dimnames' [1] not equal to array extent
> bars.new = matrix(bars[-1,],nrow=1); rownames(bars.new)=c('b');
> bars.new
  [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14] [,15] [,16] [,17]
b   10   10   10   10   10   10   10   10   10    10    10    10    10    10    10    10    10
  [,18] [,19] [,20] [,21] [,22] [,23] [,24] [,25]
b    10    10    10    10    10    10    10    10