2017-10-16 3 views
0

私はggplotに勾配の色付けスキームを使用したいデータがあり、それからいくつかのポイントに注釈を付けます。geom_pointにgeom_text_repelレイヤーをscale_colour_gradient2で塗りつぶしてください

マイデータ:

ここ
df <- data.frame(id = rep(LETTERS,100), 
       val1 = rnorm(100*length(LETTERS)), val2 = rnorm(100*length(LETTERS)), 
       sig = runif(100*length(LETTERS),0,1), 
       col = NA,stringsAsFactors = F) 

私は注釈を付け、それらに色を与えるしたいのですがいくつかのポイントを選択:

df$col[sample(nrow(df), 10, replace = F)] <- rainbow(10) 

をそしてここで私がしようとしているggplotコードです:

library(ggplot2) 
library(ggrepel) 
ggplot(df,aes(x=val1,y=val2,color=col))+ 
    geom_point(aes(color=sig),cex=2)+scale_colour_gradient2("Significance",low="darkred",mid="darkblue",high="darkred")+ 
    geom_text_repel(data=dplyr::filter(df,!is.na(col)),aes(x=dplyr::filter(df,!is.na(col))$val1,y=dplyr::filter(df,!is.na(col))$val2,label=dplyr::filter(df,!is.na(col))$id,colour=dplyr::filter(df,!is.na(col))$col))+ 
    theme_minimal()+theme(legend.position="none") 

このエラーをスローする:

Error: Discrete value supplied to continuous scale 

任意のアイデア?

答えて

3

は基本的に2つの方法があります。 1つは連続変数を塗りつぶしに、離散テキスト変数はエース呼び出しの中で色を付けることです。もう1つは、連続変数をエース内の色にマップし、エース呼び出しの外にテキストを手動でマップすることです。

第1のアプローチ - 塗りつぶしに連続的なスケールをマッピングし、塗りつぶしの美学をサポートする形状(pch = 21)を使用します。私はscale_fill_gradientnを使用し、色がデータ範囲のどこにあるかを手動で定義しました。values = scales::rescale(c(min(df$sig), median(df$sig), max(df$sig)))

は色美的に離散的な規模を(ラベルを撃退)にマッピングすることが容易であること後。しかし、一つはscale_colour_manual

library(tidyverse) 

ggplot(df,aes(x = val1, y = val2))+ 
    geom_point(aes(fill = sig), cex=2, pch = 21)+ 
    scale_fill_gradientn("Significance",colors = c("darkred", "darkblue","darkred"), values = scales::rescale(c(min(df$sig), median(df$sig), max(df$sig))))+ 
    geom_text_repel(data = dplyr::filter(df,!is.na(col)) %>% 
        mutate(col = factor(col, levels = col)), 
        aes(x = val1, y = val2, label = id, color = col), size = 6)+ 
    scale_colour_manual(values = dplyr::filter(df,!is.na(col))[,5])+ 
    theme_minimal()+ 
    theme(legend.position = "none") 

enter image description here

第2のアプローチで供給色と一致するレベルの順序を定義する必要がある - AESコール外部geom_text_repelの色を指定します。

ggplot(df,aes(x = val1, y = val2)) + 
    geom_point(aes(color= sig), cex=2) + scale_colour_gradient2("Significance",low="darkred",mid="darkblue",high="darkred")+ 
    geom_text_repel(data = dplyr::filter(df,!is.na(col)), aes(x = val1, y = val2, label = id), color = dplyr::filter(df,!is.na(col))[,5], size = 6)+ 
    theme_minimal()+ 
    theme(legend.position = "none") 

enter image description here

+0

おかげでたくさんの@missuse。配色を離散化することが唯一の解決策だと思いますか? – dan

+0

@ダン、別の解決策を追加しました。編集を確認 – missuse

関連する問題