Home > OS >  How to make a stacked plot in R
How to make a stacked plot in R

Time:12-19

I have this dataframe I made and Im trying to make a stacked bar graph with two bars, one for Imp15 and the other for Imp19. Each bar will be broken down into the respective numbers in the table's columns 0,1, and Na. I know this is simple but Im having trouble getting the code to work out.

DA <- data.frame(
  Imp =c("IMP15","IMP19"),
  "0"=c(220,209),
  "1"=c(3465,3347),
  "NA"=c(501,630),
  Total=c(4186,4186)
)

CodePudding user response:

There are many (many!) online resources explaining how to create a stacked barplot in R. Without more details, such as the code you've tried and/or what error messages you are getting, we can only guess at potential solutions. E.g. do either of these approaches help? Or do you want your plot to look different?

DA <- data.frame(
  Imp=c("IMP15","IMP19"),
  "0"=c(220,209),
  "1"=c(3465,3347),
  "NA"=c(501,630),
  Total=c(4186,4186)
)

rownames(DA) <- c("IMP15","IMP19")
colnames(DA) <- c("Imp", "0", "1", "NA", "Total")

par(mar=c(5.1, 4.1, 4.1, 8.1), xpd=TRUE)
barplot(t(as.matrix(DA[,2:5])),
        legend.text = c("0", "1", "NA", "Total"),
        args.legend = list(x = "right",
                           inset=c(-0.2,0)))


library(tidyverse)

DA <- data.frame(
  Imp=c("IMP15","IMP19"),
  "0"=c(220,209),
  "1"=c(3465,3347),
  "NA"=c(501,630),
  Total=c(4186,4186),
  check.names = FALSE
)

DA %>%
  pivot_longer(-Imp) %>%
  ggplot(aes(x = Imp, y = value, fill = name))  
  geom_col(position = "stack")

Created on 2021-12-19 by the reprex package (v2.0.1)

  •  Tags:  
  • r
  • Related