2016-07-22 5 views
0

積み重ねたIDバープロットを作成しようとしていますが、ggplot2はデータをまとめて保持しています。ggplot2スタックバープロットのトラブルシューティング

セクタごとにそれぞれのカテゴリごとに積み上げプロットを提供する代わりに、direct,indirect.downおよびindirect.upのカテゴリをまとめて集計します。

test.df = data.frame(scenario=(c("s1", "s1", "s1", "s2", "s2", "s2", "s3", "s3", "s3", 
          "s1", "s1", "s1", "s2", "s2", "s2", "s3", "s3", "s3", 
          "s1", "s1", "s1", "s2", "s2", "s2", "s3", "s3", "s3")), 
       sector=(c("Agriculture", "Manufacturing", "Services", "Agriculture", "Manufacturing", "Services", "Agriculture", "Manufacturing", "Services", 
         "Agriculture", "Manufacturing", "Services", "Agriculture", "Manufacturing", "Services", "Agriculture", "Manufacturing", "Services", 
         "Agriculture", "Manufacturing", "Services", "Agriculture", "Manufacturing", "Services", "Agriculture", "Manufacturing", "Services")), 
       loss=(runif(27,0,1000)), shock=(c("direct", "indirect.up", "indirect.down","direct", "indirect.up", "indirect.down","direct", "indirect.up", "indirect.down", 
         "direct", "indirect.up", "indirect.down","direct", "indirect.up", "indirect.down","direct", "indirect.up", "indirect.down", 
         "direct", "indirect.up", "indirect.down","direct", "indirect.up", "indirect.down","direct", "indirect.up", "indirect.down"))) 

library(ggplot2) 

ggplot(test.df, aes(x=sector, y=loss)) + geom_bar(stat = "identity", aes(fill=shock)) + facet_wrap(~ scenario) + coord_flip() 

私はそれが各セクタへの衝撃が積層されているかという点で、このようになりたい:

enter image description here

答えて

1

あなたのサンプルデータでは、各sectorshockの一種類のみを持っているためですそれに関連付けられています。

table(test.df$sector, test.df$shock) 

#    direct indirect.down indirect.up 
# Agriculture  9    0   0 
# Manufacturing  0    0   9 
# Services   0    9   0 

sectorshockの間でいくつかのより多くの関連付けを作成するために、いくつかのデータを追加:

df2 <- test.df 

df2$shock[df2$shock == "indirect.down"] <- "indirect.up" 
df2$shock[df2$shock == "direct"] <- "indirect.down" 

test.df <- rbind(test.df, df2) 

table(test.df$sector, test.df$shock) 

#    direct indirect.down indirect.up 
# Agriculture  9    9   0 
# Manufacturing  0    0   18 
# Services   0    9   9 

は今、あなたのコードをテストします。

library(ggplot2) 

ggplot(test.df, aes(x=sector, y=loss)) + 
geom_bar(stat = "identity", aes(fill=shock)) + 
facet_wrap(~ scenario) + coord_flip() 

enter image description here

+0

を感謝Sumedh、私は今、整流されています問題。 –

関連する問題