2016-12-27 2 views
0

私は他の解決策を見ましたが、ggplot内の論理を正しく動作させることはできません。私は以下の機能を持っています。 2つの列と共にデータフレームが渡され、散布図としてプロットされます。私が使用してコールggplot2 - カラム名でデータフレームを渡す

scatter_plot2 <- function(df, xaxis, yaxis){ 
     b <- ggplot(data = df, aes_string(xaxis, yaxis), environment = environment()) 
     gtype <- geom_point(aes(alpha = 0.2, color = yaxis > 0)) 
     sm <- geom_smooth(formula = xaxis ~ yaxis, color="black") 
     b + gtype + sm + theme_bw() 
    } 

scatter_plot2(train_df, "train_df$signal", "train_df$yhat5") 

===

color = yaxis > 0

は以下に(y軸)上の点 "緑" で0とするものをプロットすることが意図されています"赤"。私は軸に正しく表示するために文字列名を取得することができますが、私は正しく動作するように論理を得ることができません。

助けてください。

答えて

1

独自の関数を作成するので、必要な色を事前に計算するだけです。データフレームと変数を渡すので、いくつかの標準的な評価が必要です(既にaes_stringを使ってこれを行っています)。

私はいくつかのaes呼び出しが明示的にすること、そしてあなたのスムーズな式y~xを作る,,単鎖にggplot文を入れて、コードを少しクリーンアップ。変数を渡すときには、引用された名前を渡すだけで$を使用したくない場合もあります。

library(dplyr) 
library(ggplot2) 

scatter_plot2 <- function(df, xaxis, yaxis){ 

    df <- mutate_(df, color = ~ifelse(yaxis > 0, "green", "red")) 

    ggplot(data = df, aes_string(x = xaxis, y = yaxis)) + 
     geom_point(aes(alpha = 0.2, color = color)) + 
     geom_smooth(formula = y ~ x, color =" black") + 
     scale_color_identity() + 
     theme_bw() 
} 

コールは、(例えばirisを使用して)次のようになります。その結果

scatter_plot2(iris, "Sepal.Width", "Sepal.Length") 

enter image description here

+0

はありがとうございました!ありがとうございました!ありがとうございました!! –

関連する問題