2016-12-21 3 views
0

私の最初のデータフレームです。 ggplotを作るためにaes_stringを使ってgeom_pointの色を動的列から変更する

data.df

x y z label 
2 3 4 1 
1 2 3 2 
2 4 3 3 

、唯一の1列(ラベル)がある場合、これは動作します:

g <- ggplot(data.df) + 
     geom_point(data = data.df, aes(x= x, y= y, 
     color = ifelse((label == 2), "a", "b")+ 
     scale_colour_manual(values= c("a" = "blue", "b" = "green")) 

    return g 

は "マージ" というボタンをクリックすると、新しい列動的に追加されます:

x y z label label2 
2 3 4 1  1 
1 2 3 2  2 
2 4 3 3  2 

ggplotではラベル列(label2、label3 ...の可能性があります)の代わりに最後の列を入力し、ggplotを更新します。

私は2つの方法を試しました。

g <- ggplot(data.df) + 
     geom_point(data = data.df, aes(x= x, y= y, 
     color = ifelse((data.df[, ncol(data.df)] == 2, "a", "b")+ 
     scale_colour_manual(values= c("a" = "blue", "b" = "green")) 


    return g 

data.df [、NcoI部位(data.df)]を使用している間、私はエラーを取得してい示されているように:

Error: Aesthetics must be either length 1 or the same as the data (40): x, y, colour

私はaes_stringの代わりにAESを使用することができます感じています。

label <- paste("label", counter , sep="") 

g <- ggplot(data.df) + 
     geom_point(data = data.df, aes_string(x= "x", y= "y", 
     color = ifelse((label == 2), a, b))) + 
     scale_colour_manual(values= c("a" = "blue", "b" = "green")) 

私はこのエラーを取得しています:

Error in ifelse((label == 2), a, b))), : object a not found 
+1

これはPythonとどのように関連していますか?また、「これらのどれも動作していないように思われる」とは、プログラミング問題の適切な記述ではありません。 – Goyo

+0

これを行うには、データを前処理してダイナミックラベルを作成し、次に 'ggplot'を使用します。 –

+0

再現可能なデータを含めると、手助けするのがかなり簡単になります。http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example –

答えて

0

私の意見は、ggplot2関数に入る前に動的な機能を可能にする標準的な評価を行うことです。

以下は、Standard evaluation versions of dplyr functions.を利用しています。データフレームにformatColと呼ばれる列を作成し、その上にカラースケールを設定します。

data.df <- data.frame(x = c(2, 1, 2), 
         y = c(3, 2, 4), 
         z = c(4, 3, 3), 
         label = c(1, 2, 3), 
         label2 = c(1, 2, 2)) 

library(ggplot2) 
library(dplyr) 
library(lazyeval) 

formatCol <- names(data.df)[ncol(data.df)] 
formula <- interp(~ifelse((label == 2), "a", "b"), label = as.name(formatCol)) 

plot.df <- data.df %>% mutate_(formatCol = formula) 

    g <- ggplot(plot.df, aes(x= x, y= y)) + 
     geom_point(aes(color = formatCol))+ 
     scale_colour_manual(values= c("a" = "blue", "b" = "green")) 

g 
+0

私は、このコードをテストするときに私のエラーがscale_colour_manualであることを発見しました。これは私のコードをきれいにするのを助けた。ありがとうございました! –

関連する問題