Home > Enterprise >  How to add frequency to barplot for inbuilt barplot r function
How to add frequency to barplot for inbuilt barplot r function

Time:08-04

I have a dataframe as follows:

tab=cbind(AR, PR, GR)

tab

          AR    PR   GR
High      340   301  182
Low       97    112  271
Moderate  211   235  195

I created barplot of the data using barplot function

barplot(cbind(AR, PR, GR), col=c("purple", "green", "cyan"),beside=FALSE)
legend("topleft", legend = c("High", "Low", "Moderate"), fill =  c("purple", "green", "cyan"))

output

Now, I want to add the frequency inside the barplot. I tried using labels=tab, but it did not work.

CodePudding user response:

I think you need to draw them on using text. Here's a full reprex:

AR <- c(High = 340, Low = 97, Moderate = 211)
PR <- c(High = 301, Low = 112, Moderate = 195)
GR <- c(High = 182, Low = 281, Moderate = 195)

barplot(cbind(AR, PR, GR), col=c("purple", "green", "cyan"), beside = FALSE)

text(x = rep(c(0.7, 1.9, 3.1), each = 3),
     y = c(apply(cbind(AR, PR, GR), 2, \(x) c(0, cumsum(head(x, -1)))   x/2)),
     label = c(AR, PR, GR))

legend("topleft", legend = c("High", "Low", "Moderate"),
       fill =  c("purple", "green", "cyan"))

Since the question is tagged with ggplot2, here's how you could achieve a nicer aesthetic result using ggplot:

library(tidyverse)

data.frame(AR, PR, GR) %>%
  rownames_to_column(var = "rows") %>%
  pivot_longer(-1) %>%
  ggplot(aes(name, value, fill = factor(rows, c("Low", "Moderate", "High"))))  
  geom_col()  
  geom_text(aes(label = value), position = position_stack(vjust = 0.5),
            size = 5)  
  scale_fill_brewer(palette = "Pastel1")  
  labs(x = NULL, y = NULL, fill = NULL)  
  theme_minimal(base_size = 16)  
  theme(panel.grid.major.x = element_blank(),
        axis.line.y = element_line()) 

enter image description here

Created on 2022-08-03 by the reprex package (v2.0.1)

  • Related