ggplot の if else 条件でレイヤーを追加するには質問する

ggplot の if else 条件でレイヤーを追加するには質問する

たとえば、特定の条件が満たされた場合、ggplot で 2 つのレイヤーをプロットし、1 つにはポイントを、もう 1 つには線をプロットするとします。

基準のないコードは次のようになります。

library("ggplot2")

# Summarise number of movie ratings by year of movie
mry <- do.call(rbind, by(movies, round(movies$rating), function(df) {
  nums <- tapply(df$length, df$year, length)
  data.frame(rating=round(df$rating[1]), year = as.numeric(names(nums)), number=as.vector(nums))
}))

p <- ggplot(mry, aes(x=year, y=number, group=rating))

p + 
geom_point()+
geom_line()

ここで、線だけでなく点もプロットするための条件は、tmp.data というオブジェクトが式「値なし」と等しくないことです。

tmp.data<-c(1,2,3) # in this case the condition is fulfilled

# attempt to plot the two layers including the condition in the plotting function
p+ 
  if(tmp.data[1]!="no value"){ geom_point()+}
  geom_line()

失敗します....

Error: unexpected '}' in:
"p+ 
if(tmp.data[1]!="no value"){ geom_point()+}"

geom_line() geom_line:
stat_identity:
position_identity: (幅 = NULL、高さ = NULL)

ベストアンサー1

これは ggplot2 2.1.0 を使用して実行されました。括弧をステートメント全体を含むように変更するだけで、OP が望んでいたことを正確に実行できると思いますif

SwtichTか かに応じて水平線を追加する例を示しますF。まず、条件がTRUE

library(ggplot2)

df<-data.frame(x=1:10,y=11:20)
Switch=T

ggplot(df,aes(x,y))+
{if(Switch)geom_hline(yintercept=15)}+
  geom_point()

ここに画像の説明を入力してください

さて、同じことですが、条件はFALSE

df<-data.frame(x=1:10,y=11:20)
Switch=F

ggplot(df,aes(x,y))+
{if(Switch)geom_hline(yintercept=15)}+
  geom_point()

ここに画像の説明を入力してください

おすすめ記事