2012-08-11 46 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") 

を使用して、この表を溶融しました。私は

ggplot(melted.data,aes(x=activity,y=responses))+geom_bar(aes(fill=haveused)) 
を試してみた番号、x軸、y軸での応答の頻度、およびイエスの分布を示す各バーに活動して積み上げ棒グラフを作成したいと

をdontknows

しかし、私はそれが適切な解決策ではないと恐れています

何か助けが大変ありがとうございます。

答えて

5

解決策について正しくはないとは言わなかった。しかし、問題と解釈される問題とその解決策の1つは次のとおりです。

  • x軸の目盛りのラベルが相互に衝突します。解決策 - 目盛りラベルを回転させます。
  • ラベル(および対応するバー)が表示される順序は、元のデータフレーム内の順序と同じではありません。解決策 - 要因 '活動'のレベルを並べ替えます。バー内のテキストを配置する
  • には、次のスタートかもしれない0.5

position_stackvjustパラメータを設定します。

# 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 
関連する問題