0

I have created the below data frame and want to create a stacked bar chart showing the percentages of available habitats (main.Avail) alongside the percentage of used habitats (main.Used50K). I have used the barplot(as.matrix(subset)) function but I can't seem add legends indicating the different habitat categories (NA, BOG, F, OIP, RG, RIP, UM) in the stacked bar charts. How can I do this?

  main.Hab main.Avail main.Used50K
1     <NA>   4.186001    0.7795595
2      BOG   8.128698    1.4224366
3        F  12.294499    0.4780462
4      OIP  43.902867   69.9860934
5       RG   7.488637    2.3009635
6      RIP   9.713074   22.7798587
7       UM  14.286223    2.2530800
m0nhawk
  • 22,980
  • 9
  • 45
  • 73

1 Answers1

0

We can do this by changing the row.names

m1 <- as.matrix(df1[-1])
row.names(m1) <- df1[,1]
barplot(m1, legend = TRUE)
akrun
  • 874,273
  • 37
  • 540
  • 662
  • you solved the problem, but I suspect that the OP was looking for something more like `barplot(m1, beside=TRUE, col=rainbow(7), legend = TRUE)` – G5W Mar 11 '17 at 22:39
  • Thank you. This code: m1 <- as.matrix(df1[-1]) row.names(m1) <- df1[,1] barplot(m1, legend = TRUE) seems to have worked. However the legend is overlapping with the barplot. Do you know how to separate the legend from the bar plot? – M. Thornton Mar 12 '17 at 20:46
  • @M.Thornton You can use the `args.legend` to change the position. Please check [this](http://stackoverflow.com/questions/18688847/position-legend-of-a-stacked-bar-plot) – akrun Mar 13 '17 at 02:44