1

我正在使用 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'))
4

1 回答 1

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
于 2014-03-12T15:15:31.910 回答