2017-05-22 8 views
1

ggplot2のグラフを条件付きカラーで作成したいので、データポイントが別の列の条件を尊重している場合は"green"になります。それ以外の場合は、あらかじめ定義されたカラーパレット。ggplot color条件付き他の列の定義済みカラーパレット

私はggplot2にSOについて、条件付きカラーで見てきた答えは、手動scale_fill_manualまたはscale_color_manualherehereを使用して色を示すためにお勧めします。

これは、多くのカラーカテゴリを持っている場合や、RColorBrewerまたはViridisの美しい定義済みカラーパレットの1つを使用したい場合には、あまり理想的ではありません。

ここに私のrepdoducibleの例では、私のattempである:

library(ggplot2) 
library(RColorBrewer) 

# get data 
    data("mtcars") 

ggplot(mtcars, aes(x=qsec, y=hp, color= ifelse(cyl < 6, "green", factor(carb)))) + 
    scale_colour_brewer(type = "seq", palette = "Reds") + 
    geom_point() + 
    theme_bw() 

enter image description here

答えて

1

別のオプションは、それは別の層を追加するのと同じくらい短いではありませんが、私はプロットが少しクリーナー(あなたが重複ポイントではない)だと思います。あなたが@Danielに答えるため

df <- mtcars 
df$col <- ifelse(df$cyl < 6, "cyl < 6", as.character(df$carb)) 
non_green <- unique(df$col[df$col != "cyl < 6"]) 
non_green <- non_green[order(non_green)] 

ggplot(df, aes(x=qsec, y=hp, colour= col)) + 
    scale_color_manual(values = c(setNames(brewer.pal(length(non_green), name = "Reds"), non_green), "cyl < 6" = "green")) + 
    geom_point() + 
    theme_bw() 

enter image description here

3

どのように特定の色にしたいデータのサブセットのみで追加ポイントの層を追加することについてはどうですか?

mtcars$condition <- with(mtcars, ifelse(cyl < 6, 1, 0)) 

ggplot(mtcars, aes(x=qsec, y=hp, color= factor(carb))) + 
    geom_point() + 
    geom_point(data = subset(mtcars, condition == 1), color = "green") + 
    scale_colour_brewer(type = "seq", palette = "Reds") + 
    theme_bw() 

enter image description here

+0

感謝。私はこれがおそらく最も単純な解決策だと思っています。私はあなたに答えました。私はMathewへの答えを与えてくれました。彼の答えは、チャートが凡例に明らかになっていれば、メッセージを受け取るありがとう! –

+0

ああ...。私は凡例を変更したくないという印象を受けました。私はMikeに非常に似た解決策を持っていましたが、伝説の滞在基準が好まれていると思いました。 –

関連する問題