[英]ggplot2 to generate a geom_bar()
我下表具有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
我的條形圖代碼是:
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"))
我的問題是,如何使用ggplot2
和geom_bar()
生成此條形圖。 出於可視化目的,我希望生成兩個堆疊的條形,一個包含接受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))
說明:這很簡單-創造ggplot
與x(financial_assistance)和y(百分比)的變量,並創建geom_bar
。 關於geom_bar
唯一要記住的是,默認情況下它會計算“ x”的數量,並將其顯示為鋼筋高度。 在這種情況下,您想使用y變量作為值,所以這就是stat="identity"
位。 aes(fill=students1)
在此處為堆疊的條形添加兩種顏色。
更新:剛注意到我誤讀了您試圖實現的目標,對代碼進行了更正。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.