[英]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.我现在想在一个条形图中 plot 数据,以便每个变量显示 0 和 1 的数量。 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
:如果要显示相邻的条,可以将 position 设置为dodge
:
df %>%
pivot_longer(cols = everything()) %>%
ggplot() +
geom_bar(aes(x = name,
fill = factor(value)),
position = "dodge") +
labs(fill = "Group")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.