2017-10-08 89 views
0

我想創建一個barplot,顯示按單身或結婚分組的大學畢業生或非大學畢業生分組的工會和非工會工人的平均小時工資。雖然我設法構建了具有兩個因素分組的可通過的barplot,但我無法弄清楚如何使用三個因子分組來完成此操作。我所看到的例子有三個因素只是頻率計數,所以我不確定如何將所有因素中的另一個變量的平均值併入到圖中。我所希望創造的東西,看起來像這樣(在Stata創建): Average Hourly Wage by Union Status, Marital Status, and College Graduation 我的代碼如下所示:具有多個因素分組和多變因子均值的水庫羣

levelbar = tapply(wage, list(as.factor(union), as.factor(married), 
as.factor(collgrad)), mean) 
par(mfrow = c(1, 2)) 
barplot(levelbar, beside = TRUE) 
barplot(t(levelbar), beside = TRUE) 

當我運行這一點,但是,我收到錯誤:

Error in barplot.default(levelbar, beside = TRUE) : 
'height' must be a vector or a matrix 

任何幫助,將不勝感激。我敢肯定,ggplot可能在這裏很有用,但我沒有很多使用該軟件包的經驗。

回答

0

這是一個使用ggplot和內置數據集泰坦尼克號的可重現示例。

請注意,我們首先計算平均值,並使用stat = identity來確保我們將這些數據導入到圖中。

# Format the Titanic dataframe 
Titanic_df <- Titanic %>% as_tibble() 

# Make Class, Sex, Age, and Survived factors 
for (col in c("Class", "Sex", "Age", "Survived")) { 
    Titanic_df[[col]] <- factor(Titanic_df[[col]]) 
} 

# Get by group means 
means <- Titanic_df %>% 
    group_by(Class, Sex, Survived) %>% 
    summarise(
    mean_n = mean(n) 
) 

# Plot: facets are the Classes, bar colors are the two Sexes, and the groupings in each facet are Survived vs. Not Survived 
ggplot(data = means) + 
    geom_bar(aes(x = Survived, y = mean_n, fill = Sex), stat = "identity", position = "dodge") + 
    facet_wrap(~ Class) 

enter image description here

+0

謝謝!如果我想消除第三列出現b/c聯盟因素水平有NAs,我會在那裏?我試過 '意味着<- nlsw_df %>% na.omit()%>% GROUP_BY(工會,已婚,collgrad)%>% 總結( mean_wage =平均值(工資) )' 我試着 'ggplot(數據= na.omit(單元))+ geom_bar(AES(X = collgrad,Y = mean_wage,填充=聯盟),STAT = 「同一性」,位置= 「躲閃」)+ facet_wrap( 〜已婚) 我試過 '(col in c(「union」,「married」,「collgrad」)){ nlsw_df [[col]] < - factor(nlsw_ df [[col]],exclude = NA) }' –

+0

儘管您已經清除了NA值,但仍然存在NA因素級別。在na.omit()'(或'drop_na(union)'後面連接'droplevels()',如果你只想在union列中放棄NAs行)應該做到這一點。 – amanda

+0

嗨阿曼達, 感謝您的答覆。我認爲你說得對,這是正確的做法,但由於某種原因,我無法實現它。儘管在na.omit()之後鏈接了小滴(),但第三個未使用的NA小節仍然顯示在圖上。我已經運行的代碼是: '意味着<- nlsw_df %>% na.omit(工會)%>% droplevels(工會)%>% GROUP_BY(工會,已婚,collgrad)%>% 總結( mean_wage =平均(工資) ) ggplot(數據=單元)+ geom_bar(AES(X = collgrad,Y = mean_wage,填充=聯盟),STAT = 「同一性」,位置= 「躲閃」)+ facet_wrap(〜已婚)' –