2017-06-04 9 views
1

私は棒グラフがグループごとに降順になるように、ggplotでRのグループ化された棒グラフをフォーマットしようとしています。これは私の現在のプロットである:R ggplotグループ内のバーの並べ替え

> top_categories 
        Category Count Community 
1   Singer-Songwriters 151   1 
2   Adult Alternative 147   1 
3     Dance Pop 95   1 
4      Folk 89   1 
5   Adult Contemporary 88   1 
6     Pop Rap 473   2 
7   Gangsta & Hardcore 413   2 
8      Soul 175   2 
9     East Coast 170   2 
10    West Coast 135   2 
11 Album-Oriented Rock (AOR) 253   3 
12  Singer-Songwriters 217   3 
13     Soft Rock 196   3 
14      Folk 145   3 
15  Adult Contemporary 106   3 
16      Soul 278   4 
17      Blues 137   4 
18      Funk 119   4 
19    Quiet Storm 76   4 
20     Dance Pop 74   4 
21    Indie & Lo-Fi 235   5 
22    Indie Rock 234   5 
23   Adult Alternative 114   5 
24   Alternative Rock 49   5 
25  Singer-Songwriters 47   5 

このコードで作成:関連の記事からの提案に基づき

ggplot(
    top_categories, 
    aes(
    x=Community, 
    y=Count, 
    group=Category, 
    label=Category 
) 
) + 
    geom_bar(
    stat="identity", 
    color="black", 
    fill="#9C27B0", 
    position="dodge" 
) + 
    geom_text(
    angle=90, 
    position=position_dodge(width=0.9), 
    hjust=-0.05 
) + 
    ggtitle("Number of Products in each Category in Each Community") + 
    guides(fill=FALSE) 

、私はしました。このデータフレームに基づいて

current chart

reorder関数を使用しようとしましたが、Countを因子に変換しようとしました。両方とも結果がtの順序を壊しているようです彼は(要因で)このような無意味な方法でテキスト対バーやプロットを再スケール:

messed up factor plot

私はこのグループ内の順序を達成する可能性がある方法上の任意のヒントを?ありがとう!

+0

あなたは 'dput'にデータを提供することができます – Masoud

答えて

4

カテゴリ別にグループ化すると、バーはデータフレーム内のカテゴリの出現順に並べられます。 Countが減少すると、行がすでに順序付けされているので、これはCommunity 1と2でうまくいきます。しかし、コミュニティー3では、カテゴリー "シンガーソングライター"がデータフレーム内の最初のocccurring Categoryであるので、それが最初に置かれます。 ID変数によって代わりにグループ化

は、問題を解決します

top_categories$Id=rep(c(1:5),5) 

ggplot(
    top_categories, 
    aes(
    x=Community, 
    y=Count, 
    group=Id, 
    label=Category 
) 
) + 
    geom_bar(
    stat="identity", 
    color="black", 
    fill="#9C27B0", 
    position="dodge" 
) + 
    geom_text(
    angle=90, 
    position=position_dodge(width=0.9), 
    hjust=-0.05 
) + 
    ggtitle("Number of Products in each Category in Each Community") + 
    guides(fill=FALSE) 

enter image description here

関連する問題