[英]ggplot2 to generate a geom_bar()
I have the following table in R Studio , and I am trying to create a geom_bar()
with ggplot2
to represent the percentage of students that received financial assistance and those who did not. 我下表具有R中工作室 ,我试图创建一个
geom_bar()
与ggplot2
来代表接受资助的学生比例和那些谁没有。
comparison_table <- data.frame(Students1, Percentage1, financial_assistance1, stringsAsFactors = F)
comparison_table
Students1 Percentage1 financial_assistance1
1 PELL 0.4059046 True
2 NOPELL 0.5018954 False
3 LOAN 0.4053371 True
4 NOLOAN 0.2290538 False
My code for the bar plot is: 我的条形图代码是:
PELL<-mean(na.omit(completion_rate_based_on_financial_assistance$percent_of_students_with_Pell_Grant_and_completed_in_4_years))
NOPELL<-mean(na.omit(completion_rate_based_on_financial_assistance$percent_of_students_without_Pell_Grant_and_completed_in_4_years))
LOAN<-mean(na.omit(completion_rate_based_on_financial_assistance$percent_of_students_with_federal_loan_and_completed_in_4_years))
NOLOAN<-mean(na.omit(completion_rate_based_on_financial_assistance$percent_of_students_without_federal_loan_and_completed_in_4_years))
tab1<-cbind(PELL,LOAN)
tab2<-cbind(NOPELL,NOLOAN)
tab<-rbind(tab1,tab2)
rownames(tab) <- c("PELL","LOAN")
colnames(tab) <- c("With Financial Help","Without Financial Help")
barplot(tab,beside = F,legend.text= rownames(tab),xlab = "Financial Help",col=c("lightblue","pink"))
My question is, how can I generate this bar plot using ggplot2
and geom_bar()
. 我的问题是,如何使用
ggplot2
和geom_bar()
生成此条形图。 For visualization purposes, I wish to generate two stacked bars, one that contains the percentage of students that received Pell Grants and Loans (PELL & LOAN) and other bar that contains the percentage of students that did not received Pell Grants and Loans (NOPELL & NOLOAN) . 出于可视化目的,我希望生成两个堆叠的条形,一个包含接受Pell助学金和贷款的学生百分比(PELL&LOAN) ,另一个包含不接受Pell助学金和贷款的学生百分比(NOPELL& NOLOAN) 。
tb<-data.frame(students1=c("PELL","NOPELL","LOAN","NOLOAN"), percentage1=c(40,50,40,23), financial_assistance1=c(TRUE,FALSE, TRUE, FALSE))
g<-ggplot(tb,aes(financial_assistance1,percentage1))
g+geom_bar(stat="identity",aes(fill=students1))
Explanation: It's pretty simple - create the ggplot
with the x (financial_assistance) and y (percentage) variables, and create the geom_bar
. 说明:这很简单-创造
ggplot
与x(financial_assistance)和y(百分比)的变量,并创建geom_bar
。 Only thing to remember about the geom_bar
is that it defaults to counting how many cases of "x" and showing that as the bar height. 关于
geom_bar
唯一要记住的是,默认情况下它会计算“ x”的数量,并将其显示为钢筋高度。 In this case, you want to use the y variable as the value, so that's the stat="identity"
bit. 在这种情况下,您想使用y变量作为值,所以这就是
stat="identity"
位。 The aes(fill=students1)
is there to add the two colours for the stacked bars. aes(fill=students1)
在此处为堆叠的条形添加两种颜色。
UPDATE: Just noticed I misread what you tried to achieve, edited the code to correct for it. 更新:刚注意到我误读了您试图实现的目标,对代码进行了更正。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.