2017-12-23 9 views
1

にカウントラベルを追加します。私は、グラフを棒にラベルを追加することに苦労する傾向があります。私は、このグラフでは、各バーの横カウントラベルを追加しようとしていますが、番号が正しい場所に配置されていません。クラスタ化された棒グラフggplot2

bargraph

をここに私のデータは、(大きなデータセットのサブセット)です。

County Group Plan1 Plan2 
County1 Group3 597  513 
County2 Group3 182  130 
County3 Group3 180  126 
County4 Group3 266  284 
County5 Group3 258  171 
County6 Group3 159  71 
County7 Group3 187  157 
County8 Group3 101  84 

は、私は他の記事から()の提案をgeom_text使用しようとしましたが、同様の結果を得る続けました。

コード:

df.g <- gather(df, key=`Plan Type`, value=value, -County, -Group) 

ggplot(df.g[df.g$Group == "Group3", ], 
     aes(County, value)) + 
    geom_bar(aes(fill = `Plan Type`), 
      stat = "identity", colour = "black", position = "dodge") + 
    scale_fill_brewer(palette = "Set2") + 
    ggtitle("Enrollees per Plan by County") + 
    theme(plot.title = element_text(hjust=0.5)) + 
    coord_flip() + 
    geom_text(aes(x = County, y = value, label = value, 
       hjust = ifelse(sign(value) > 0, 1, 0)), 
      position = position_dodge(width = 1)) 

どのように私はこのグラフに正しくカウントラベルを追加することができますか?何かアドバイス/提案をありがとう!

答えて

0

これを試してみてください:

library(tidyr) 

df.g <- gather(df, 
#personal preference: avoid using variable names with spaces; looks cleaner that way. 
       key = Plan.Type, 
       value = value, 
       -County, -Group) 

ggplot(filter(df.g, Group == "Group3"), 
     aes(x = County, y = value, 
      fill = Plan.Type, 
      label = value)) + 
    geom_col(position = "dodge") + 
    geom_text(position = position_dodge(width = 0.9), 
      hjust = 0) + 
    # + other title/theme options 
    coord_flip() 

plot

関連する問題