I have a subset data3
of 50 factors and I want to make a barplot of all of them. I know how to do it one by one but I would like to know if there is a way of doing it for the whole dataset at once:
barplot(prop.table(table(data3$factor1)))
One option would be to loop over the columns, get the proportions
and plot it in from the list
, save it in a pdf
pdf("testing.pdf")
lst1 <- lapply(data3, function(x) barplot(proportions(table(x))))
dev.off()
Or another option is to convert to 'long' format with pivot_longer
and plot with ggplot
library(dplyr)
library(tidyr)
library(ggplot2)
data3 %>%
pivot_longer(cols = everything()) %>%
count(name, value = factor(value)) %>%
group_by(name) %>%
mutate(prop = n/sum(n)) %>%
ungroup %>%
ggplot(aes(x = name, y = prop, fill = value)) +
geom_col()