躲闪的条形图,在Ggplot2中具有多个二进制变量

时间:2019-02-08 19:27:22

标签: r ggplot2 dplyr bar-chart tidyverse

我想创建一个图表,显示基于第三个变量(年份)的三个不同变量(总计,面试,雇用)中“是”的票数。值得注意的是,没有实际的总计变量,只是总的观测值

我正在ggplot2中尝试执行此操作,但是我尝试执行的所有操作均未产生所需的结果。我可以很容易地使用geom_bar进行躲避和绘制,但是我不确定如何表示2个不同的变量。

 app <- structure(list(Applicant_Name = c("Aaraf", "Alaina", 
 "Aleena", "Alejandra", "Alexa", "Alexander", 
 "Alexandra", "Alexandra", "Alexandria", 
 "Alexis"), Interview = c("No", "No", "Yes", "Yes", "No", 
 "Yes", "Yes", "Yes", "Yes", "Yes"), Hire = c("No", "No", "Yes", 
 "No", "No", "No", "No", "No", "Yes", "Yes"), Year = c(2022, 2020, 
 2021, 2021, 2022, 2022, 2020, 2020, 2020, 2022), School = c("School of Business", 
 "Columbian Coll of Arts & Sci", "Milken Inst Sch of Public Hlth", 
 "Columbian Coll of Arts & Sci", "School of Engin & App Sc", "Columbian Coll of Arts & Sci", 
 "Columbian Coll of Arts & Sci", "Columbian Coll of Arts & Sci", 
 "School of Business", "Columbian Coll of Arts & Sci"), Major = c("Pre-Business Administration", 
 "Biological Anthropology", "Public Health", "Biological Anthropology", 
 "Systems Engineering", "Arts & Sciences", "Neuroscience", "English", 
 "International Business", "Arts & Sciences"), Ethnicity = c("Black or African American", 
 "White", "White", "Nonresident alien", "White", "White", "Race/ethnicity unknown", 
 "Two or More Race Codes", "Black or African American", "Black or African American"
 ), Sex = c("Female", "Female", "Female", "Female", "Female", 
 "Male", "Female", "Female", "Female", "Female"), GPA = c(3.221428, 
 3.230158, 3.429268, 3.576595, 3.86, 4, 3.460759, 3.89315, 3.227631, 
 1.433333)), row.names = c(NA, -10L), class = c("tbl_df", "tbl", 
 "data.frame"))

 ggplot(app, aes(Year, ..count..)) + geom_bar(aes(fill = Hire), position = "dodge")

理想情况下,我想要一个图表,其中按年份细分了我们的申请人总数(所有观察结果),紧接着是面试总数=是,旁边是雇用总数=是。

这是一个具有我可爱艺术能力的视觉例子。 https://imgur.com/a/mGyzBfJ

1 个答案:

答案 0 :(得分:3)

使用dplyrtidyr直接获取要绘制的数据:

library(dplyr)
library(tidyr)
library(ggplot2)
app2 <- app %>% 
  group_by(Year) %>% 
  summarise(Total = n(),
            Interviewed = sum(Interview == "Yes"),
            Hired = sum(Hire == "Yes")) %>% 
  gather( "category", "counts", -Year)

然后进行直接绘制:

ggplot(app2, aes(Year, counts)) + 
  geom_col(aes(fill = category), position = "dodge")

enter image description here