1

I am trying to add percentages on top of my barplot().

enter image description here

I have been looking and found that this is possible with ggplot, but I am doing this with barplot() and I can't find a way to do it. I tried label.bars, but apparently it is not part of this function.

This is my code:

barplot(table(marriage$year, marriage$dummy) , 
  beside=T, ylab="Frequency", 
  main="Distribution of Opposition and Support on Marriage Equality", 
  col= c("lightblue" , "lightgreen"), 
  names.arg=(c("1988", "2010")) , 
  legend.text = c("Support", "Oppose"), 
  ylim = c(0, 1000))

Any ideas?

Thank you!

jay.sf
  • 60,139
  • 8
  • 53
  • 110
Alpaca Paw
  • 61
  • 3
  • 1
    It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Mar 09 '21 at 08:01
  • Thank you @MrFlick, however, I have not found a code that does what I want it to do, so I don't have any examples. I find a lot of examples with ggplot2, but none with base function barplot(). I will keep looking. Thank you for your suggestion. – Alpaca Paw Mar 09 '21 at 08:05
  • 1
    That's fine if you don't have the code, but you should be able to include sample data that we can copy/paste into R for testing. Provide sample values for the `marriage` so we don't have to make them up ourselves to test possible solutions. It makes it much easier to help you. – MrFlick Mar 09 '21 at 08:07

1 Answers1

1

Store the table output in an object (here tab) as well as the invisible barplot output (here b). Then put it in text using proportions. Pretty easy :)

b <- barplot(tab <- table(mtcars$vs, mtcars$am), 
        beside=T, ylab="Frequency", 
        main="Distribution of Opposition and Support on Marriage Equality", 
        col= c("lightblue" , "lightgreen"), 
        names.arg=(c("1988", "2010")) , 
        legend.text = c("Support", "Oppose"),
        ylim=c(0, 15))
text(x=b, y=tab + .8, labels=paste0(round(proportions(tab), 1), "%"))

enter image description here

jay.sf
  • 60,139
  • 8
  • 53
  • 110