2016-12-21 6 views
0

私は積み上げ縦棒グラフを作成しようとしていますが、ggplotの期待に応えるためにデータセットをどのように作り直すかわかりません。R:GGPlotの2つの別々のカテゴリを持つスタック縦棒グラフ

私は、「死んでいる」と「負傷しました」の2​​つの列を持つデータフレームを持ち、それぞれに状態名が関連付けられています。私は、状態ごとに#injuredの縦棒グラフを#killedの上に積み重ねる必要があります。

私はこのような標準的な棒グラフを生成することができます:私はバーグラフがggplotの美学にフィルコンポーネントを追加することですが、問題は、私は」ということである「スタック」への道を知っている

ggplot(data=data, aes(x=state,y=killed)) + 
    geom_bar(position="dodge",stat="identity") + 
    coord_flip() + 
    ggtitle("Mass Shooting Killings and Injuries") + 
    labs(x="Killings and Injuries", y="State") + 
    ggtitle("Victims") 

を私のデータに合った方法でこれを行う方法がわからない。

フェイク再現性の例:

data <- read.table(text = "state killed injured 
1 Arkansas 23 50 
2 Alabama 10 20 
3 Texas 19 18 
4 Ohio 14 15 
5 Illinois 3 5", sep = "", header=T) 

library(ggplot2) 
library(reshape) 
ggplot(data=data, aes(x=state,y=killed)) + 
    geom_bar(position="dodge",stat="identity") + 
    coord_flip() + 
    ggtitle("Mass Shooting Killings and Injuries") + 
    labs(x="Killings and Injuries", y="State") + 
    ggtitle("Victims") 

enter image description here

+2

あなたが提供することができあなたのデータフレームのサンプル? – Haboryme

+0

ただ追加しました。データは独自のものなので、何かを作ったばかりです – Parseltongue

答えて

3

私はこのプロットを得るためにmeltを使用してdata.frameを再構築する必要がありました:

temp <- melt(data, id="state") 
ggplot(data=temp, aes(x=state,y=value, fill=variable)) + 
    geom_bar(position="stack",stat="identity") + 
    coord_flip() + 
    ggtitle("Mass Shooting Killings and Injuries") + 
    labs(x="Killings and Injuries", y="State") + 
    ggtitle("Victims") 

enter image description here

+0

融解が重要です – Parseltongue

関連する問題