Question

I am plotting values from multiple data sets in the same plot under a stacked bars representation using the barplot() function in R and I have noticed that the legend is not displayed if for a certain plot I have data only from one data set. Having two or more categories (i.e., data sets) raises no problem and the legend is displayed correctly. Any idea if it is possible to force it to be displayed even for only one category ? Or I have to add a dummy category if for that plot I have data available from only one data set. Thank you.

EDIT : Here is how I call the bar plot:

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'))
Était-ce utile?

La solution

An automatic coercion into a vector happened when you typed bars = bars[-1,]. For this to work, you should convert back to a matrix with named rows.

Example:

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

Does this help?

edit:

To really see the difference between the two beasts, look at this example:

> 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
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top