[Solved] How to make a stacked plot in R [duplicate]


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)

3

solved How to make a stacked plot in R [duplicate]