简体   繁体   中英

Multiple variables in one bar plot in R

I have data that is structured like the following data:

a <- c(sample(c(0,1), replace=TRUE, size=10))
b <- c(sample(c(0,1), replace=TRUE, size=10))
c <- c(sample(c(0,1), replace=TRUE, size=10))
d <- c(sample(c(0,1), replace=TRUE, size=10))
e <- c(sample(c(0,1), replace=TRUE, size=10))
f <- c(sample(c(0,1), replace=TRUE, size=10))
df <- data.frame(a,b,c,d,e,f)

I now want to plot the data in one barplot, so that for each variable it shows the amount of 0's and 1's. Any help would be very much appreciated!

if I understand it right, you just need to get the sum of elements of a column and barplot it.

Here is the solution:

# barplot of the number of 1
barplot(colSums(df))

# barplot of the number of 0
barplot(nrow(df) - colSums(df))

# combined plot with stacked bars
barplot(rbind(colSums(df),nrow(df) - colSums(df))) 

在此处输入图像描述

You can also transform the dataset into a long format and create plots with the new dataset:

library(tidyverse)

df %>%
  pivot_longer(cols = everything()) %>%
  ggplot() +
  geom_bar(aes(x = name,  
               fill = factor(value))) +
  labs(fill = "Group")

在此处输入图像描述

If you want to show the bars next to each other you may set the position to dodge :

df %>%
  pivot_longer(cols = everything()) %>%
  ggplot() +
  geom_bar(aes(x = name,  
               fill = factor(value)),
           position  = "dodge") +
  labs(fill = "Group")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM