繁体   English   中英

一个条中的多个变量 R 中的 plot

[英]Multiple variables in one bar plot in R

我的数据结构类似于以下数据:

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)

我现在想在一个条形图中 plot 数据,以便每个变量显示 0 和 1 的数量。 任何帮助将不胜感激!

如果我理解正确,您只需要获取一列元素的总和并将其绘制成条形图。

这是解决方案:

# 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))) 

在此处输入图像描述

您还可以将数据集转换为长格式并使用新数据集创建绘图:

library(tidyverse)

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

在此处输入图像描述

如果要显示相邻的条,可以将 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.

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