Skip to content
Prev 264343 / 398502 Next

Reverse legend label order in barplot

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

            
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