2017-07-05 25 views
3

Rでは、すべての行がグラフに表示されるカスタム折れ線グラフを作成しようとしていますが、グラフの凡例はカスタマイズされて2つしか表示されません。ggplotの凡例のカスタムグループ

今の私のコード:

x = data.frame(runif(20),runif(20)*2,runif(20)*3) 
names(x) = c("Run 1", "Run 2", "Run 3") 
x$Avg = apply(x, 1, mean) 
x$Step = row.names(x) 
df = melt(x, id=c("Step")) 
ggplot(df, aes(x=Step, y=value, group=variable, color=variable)) + 
    geom_line() 

結果:

enter image description here

私は、チャートショーにすべての4つのライン(1,2,3および平均を実行します)を持っていると思いますが、伝説では、「平均」と「個別のラン」を読みたいとします。ここで「平均」は選択した色ですが、「個別の実行」はグレーまたはニュートラルな色です。このようにして、たくさん走っていると、データを視覚的に見ることができますが、伝説は画面から消えてしまいます。これをどのように達成するのですか?

答えて

6

我々はsubset機能を使用し、geom_lineに二つの異なる呼び出しを使用して色を指定することができます。

ggplot()+ 
    geom_line(data = subset(df, variable != 'Avg'), 
       aes(x = Step, y = value, group = variable, colour = 'Individual Runs'))+ 
    geom_line(data = subset(df, variable == 'Avg'), 
       aes(x = Step, y = value, colour = 'Avg', group = variable))+ 
    scale_colour_manual(values = c('Avg' = 'red', 'Individual Runs' = 'grey')) 

enter image description here

1

あなたは、グループ化変数は唯一の2つのレベルがありcolorにマッピングするために作ることができます。これは、パッケージforcatsからのfct_other関数を使用するとかなり簡単です。

これは「平均」グループを維持しますが、他のすべての実行をまとめて1つのレベルにします。これはother_levelで設定できます。

library(forcats) 
df$variable2 = fct_other(df$variable, keep = "Avg", other_level = "Individual Runs") 

groupため、元の変数variableを保ち、colorのための新しい変数を使用してください。 scale_color_manualで色を設定します。

ggplot(df, aes(x = Step, y = value, group = variable, color = variable2)) + 
    geom_line() + 
    scale_color_manual(values = c("red", "grey")) 

enter image description here

関連する問題