[R] Reverse legend label order in barplot

Marc Schwartz marc_schwartz at me.com
Sat Jul 2 02:14:00 CEST 2011


On Jul 1, 2011, at 6:46 PM, Tom Porteus wrote:

> Hi list,
> 
> 
> 
> I've thus far not found a solution to my problem and hope someone can help.
> I have a data matrix and wish to plot a stacked bar plot using barplot().
> This is simple enough, but I have a problem with the legend labels being in
> the reverse order from what I want.  The default appears to have labels
> ascending bottom-to-top reflecting bottom-to-top sub-bars, but I would like
> the labels to be the reverse, i.e. ascend top-to-bottom.  Please see my
> example code below for an illustration of the problem.
> 
> 
> 
> For a reason unknown to me, if I plot a juxtaposed barplot using
> beside=TRUE, the legend labels are actually in the order I want
> (top-to-bottom labels).  Is there any way to make the legend appear the way
> I want for a stacked barplot?  If one exists, I can't find an appropriate
> argument to pass to args.legend.
> 
> Many thanks,
> 
> Tom
> 
> 
> 
> ### START ###
> 
> A <- c(50,30,10,10)
> 
> B <- c(20,10,30,10)
> 
> mat <- cbind(A,B)
> 
> rownames(mat) <- c(1,2,3,4)
> 
> barplot(mat,legend.text=rownames(mat))    #legend labels are in wrong order
> here
> 
> barplot(mat,legend.text=rownames(mat),beside=TRUE)    #correct order
> 
> ### END ###


Note that the legend in this case, by default IS in the same top to bottom order as the barplot sections in the stacked barplot. So there is a visual logic to this behavior.

Here is one workaround by reversing the rownames for 'mat' that are used in the legend text and then reversing the color sequencing passed internally to legend(). By default, for a matrix, a gamma corrected grey scale is used if you don't define the 'col' argument in barplot(). We can replicate this using the same approach with grey.colors():


  barplot(mat, legend.text = rev(rownames(mat)), 
          args.legend = list(fill = grey.colors(nrow(mat))))


Alternatively, You can use legend() separately to add the legend to the barplot in the fashion that you desire.

Thus:

  barplot(mat)

  legend("topright", legend = rownames(mat), 
         fill = grey.colors(nrow(mat)))


HTH,

Marc Schwartz

P.S. Happy Canada Day



More information about the R-help mailing list