2012-08-11 94 views
5

我正在嘗試使用ggplot 2創建堆積條形圖。我的數據以其廣泛形式顯示,如下所示。每個單元格中的數字是響應的頻率。如何通過ggplot2中的彙總數據創建堆疊條形圖

activity       yes no dontknow 
Social events      27 3 3 
Academic skills workshops   23 5 8 
Summer research     22 7 7 
Research fellowship    20 6 9 
Travel grants      18 8 7 
Resume preparation    17 4 12 
RAs        14 11 8 
Faculty preparation    13 8 11 
Job interview skills    11 9 12 
Preparation of manuscripts  10 8 14 
Courses in other campuses   5 11 15 
Teaching fellowships    4 14 16 
TAs        3 15 15 
Access to labs in other campuses 3 11 18 
Interdisciplinary research   2 11 18 
Interdepartamental projects  1 12 19 

我使用reshape2和

melted.data(wide.data,id.vars=c("activity"),measure.vars=c("yes","no","dontknow"),variable.name="haveused",value.name="responses") 

這是據我可以得到融化此表。我想創建與在x軸上活動,在y軸的響應頻率,以及表示是的分佈每個杆,NOS堆積條形圖和dontknows

我試圖

ggplot(melted.data,aes(x=activity,y=responses))+geom_bar(aes(fill=haveused)) 

但我恐怕這不是正確的解決方案

任何幫助,非常感謝。

回答

5

你還沒有說過這是不是你的解決方案是正確的。但是有些問題可能會被解釋爲問題,並且每種解決方案都有:

  • x軸刻度標記標籤互相碰撞。解決方法 - 旋轉刻度標記標籤;
  • 標籤(及其對應條)出現的順序與原始數據框中的順序不同。解決方案 - 重新排列因素「活動」的水平;
  • 要定位文本里面的酒吧position_stack設置vjust參數0.5

下面可能是一個開始。

# Load required packages 
library(ggplot2) 
library(reshape2) 

    # Read in data 
df = read.table(text = " 
activity       yes no dontknow 
Social.events      27 3 3 
Academic.skills.workshops   23 5 8 
Summer.research     22 7 7 
Research.fellowship    20 6 9 
Travel.grants      18 8 7 
Resume.preparation    17 4 12 
RAs        14 11 8 
Faculty.preparation    13 8 11 
Job.interview.skills    11 9 12 
Preparation.of.manuscripts  10 8 14 
Courses.in.other.campuses   5 11 15 
Teaching.fellowships    4 14 16 
TAs        3 15 15 
Access.to.labs.in.other.campuses 3 11 18 
Interdisciplinay.research   2 11 18 
Interdepartamental.projects  1 12 19", header = TRUE, sep = "") 

    # Melt the data frame 
dfm = melt(df, id.vars=c("activity"), measure.vars=c("yes","no","dontknow"), 
    variable.name="haveused", value.name="responses") 

    # Reorder the levels of activity 
dfm$activity = factor(dfm$activity, levels = df$activity) 

    # Draw the plot 
ggplot(dfm, aes(x = activity, y = responses, group = haveused)) + 
geom_col(aes(fill=haveused)) + 
theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.25)) + 
geom_text(aes(label = responses), position = position_stack(vjust = .5), size = 3) # labels inside the bar segments 
相關問題