簡體   English   中英

R 分組條形圖

[英]R grouped barplots

我希望有人可以將這個菜鳥指向正確的方向,試圖創建一些分組的條形圖。

我的數據(調查回復 1=是)看起來像這樣

fac_blister8 fac_lackaccess8 fac_remote8 fac_timely8 fac_none8
          <dbl>           <dbl>       <dbl>       <dbl>     <dbl>
 1            0               0           0           0         1
 2            0               0           0           0         1
 3            0               0           0           0         1
 4            0               0           0           1         0
 5            0               1           1           1         0
 6            0               0           0           0         1
 7            0               1           0           1         0
 8            0               0           0           0         1

我設法為這樣的每一列創建了一個 plot

q8 <-
  q8vars                        %>% 
  group_by(fac_lackaccess8)           %>% 
  summarise(name = n())      %>%
  mutate(fac_lackaccess8 = ifelse(fac_lackaccess8 == 0,"No","Yes")) 

q8_2 <-ggplot(q8, aes(x=fac_lackaccess8, y=name)) +
  geom_bar(stat="identity", width = 0.5, color="green", fill="green") + 
  scale_y_continuous(limits = c(0,22)) 

q8_2 +
  ylab("Count") + xlab("Working remotely and lack of resources")
  

這是可行的,但非常麻煩。 理想情況下,我希望將所有列都放在一個圖表中,並為每一列使用是/否分組條形圖。 看起來這將是相當簡單的,但我不知道如何做到這一點。

將數據重塑為長格式,計算每列中是/否的出現次數,並使用facet_wrap計算 plot 數據:

library(tidyverse)

q8vars %>%
  pivot_longer(cols = everything()) %>%
  count(name, value) %>%
  mutate(value = ifelse(value == 0, 'no', 'yes')) %>%
  ggplot(aes(x=value, y=n)) +
  geom_bar(stat="identity", width = 0.5, color="green", fill="green") + 
  facet_wrap(~name) + 
  ylab("Count") + xlab("Working remotely and lack of resources")

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM