簡體   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