2016-04-14 7 views
1

以下は、データフレームとプロットの簡単な例のコードです。条件付きでバーを色付けする方法が不思議です。私はscale_fill_manualをよく知っていますが、手動でバーの色を付けることができますが、"Satisfied"2016ファセットは、"Satisfied"2015のパーセンテージより低いパーセンテージであれば違う色にすることをお勧めします。おそらく赤い警告の境界線か、オレンジのような別の色(例のように)。条件付きでGgplot2のバーを表示

これは最良の例ではありませんが、年を上回るトップボックススコアのプロットがあれば、バーが一定の割合を下回った場合にバーの色を変更すると便利です。私は"colour = ifelse(Perc < 60, "orange", "green"の組み合わせで遊んでみましたが、動作させることができませんでした。私はifelseステートメントをどのように構造化するのか、ggplotコードのどこに配置するのかはわかりません。

Year<-c(2015, 2015, 2015, 2015, 2015, 2016, 2016, 2016, 2016, 2016) 

Service<-c("Satisfied", "Satisfied", "Satisfied", "Dissatisfied", "Dissatisfied", 
      "Satisfied", "Satisfied", "Dissatisfied", "Dissatisfied", "Dissatisfied") 

df <- data.frame(Year, Service) 

library(dplyr) 
df.prop <- df %>% 
      count(Year, Service) %>% 
      mutate(Perc = prop.table(n)) 

library(ggplot2) 
ggplot(df.prop, aes(x = Service, y = Perc, fill = Service)) + 
     geom_bar(stat = "identity", position = "dodge") + 
     geom_text(aes(label = percent(Perc)), position = position_dodge(width = 1), 
       vjust = 1.5, size = 3) + 
     scale_y_continuous(labels = percent) + 
     facet_grid(~ Year) 

答えて

1

は、データフレームに新しい変数を追加する最も簡単なことかもしれません:

df.prop$colour <- ifelse(df.prop$Service == "Satisfied" & df.prop$Perc < 0.6, "orange", NA) 

次に、あなたが行うことができます:

ggplot(df.prop, aes(x = Service, y = Perc, fill = Service, colour=colour)) + 
    geom_bar(stat = "identity", position = "dodge") + 
    geom_text(aes(label = percent(Perc)), position = position_dodge(width = 1), 
      vjust = 1.5, size = 3, colour="black") + 
    scale_y_continuous(labels = percent) + 
    facet_grid(~ Year) + 
    scale_colour_identity() 

enter image description here

を変更したい場合あなたができる条件に基づいて記入してください:

012答えを
df.prop$fill <- ifelse(df.prop$Service == "Satisfied" & df.prop$Perc < 0.6, "orange", ifelse(df.prop$Service == "Satisfied" & df.prop$Perc >= 0.6, "#00BFC4", "#F8766D")) 

ggplot(df.prop, aes(x = Service, y = Perc, fill = fill)) + 
    geom_bar(stat = "identity", position = "dodge") + 
    geom_text(aes(label = percent(Perc)), position = position_dodge(width = 1), 
      vjust = 1.5, size = 3) + 
    scale_y_continuous(labels = percent) + 
    facet_grid(~ Year) + 
    scale_fill_identity() 

enter image description here

+0

おかげで、それは素晴らしい作品。ちょうど1つのフォローアップの質問、私は色の境界を追加することができますが、輪郭の代わりにオレンジ色に実際のバーの色をどのように変更するのですか? – Mike

+0

@Mike私の編集された答えを参照してください.. – beetroot

関連する問題