2014-04-07 17 views
17

dire che voglio tracciare due layer in ggplot, uno contenente punti e un altro contenente linee se un determinato criterio è soddisfatto.if else condition in ggplot per aggiungere un ulteriore layer

Il codice senza i criteri potrebbe essere la seguente:

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() 

ora la condizione per tracciare i punti e non solo le linee sarebbero, che un oggetto chiamato tmp.data non è uguale l'espressione "no valore".

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() 

fallisce ....

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

geom_line() geom_line:
stat_identity:
position_identity: (width = NULL, height = NULL)

+0

Dove è stato definito 'C'? – James

+0

il mio male. scusa. considera le modifiche sopra – joaoal

+2

Perché non modificare semplicemente l'ordine: 'p + geom_line() + if (tmp.data [1]! =" nessun valore ") {geom_point()}' – shadow

risposta

14

Quello che stai vedendo è un errore di sintassi. Il modo più robusto mi viene in mente è:

tmp.data<-c(1,2,3) 
if(tmp.data[1]!="no value") { 
    p = p + geom_point() 
} 
p + geom_line() 

Così si compongono l'oggetto p in una sequenza, aggiungendo solo geom_point() quando il caso le dichiarazioni rese TRUE.

+0

thx per questa alternativa! – joaoal

0
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)) 
})) 

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

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

# this won't "loop through" the data points but it's what you asked for 
if (tmp.data[1]!="no value") { 
    p <- p + geom_point() + geom_line() 
} else { 
    p <- p + geom_line() 
} 
p 

g1

ma forse questo è più simile a quello che si vuole veramente?

mry$rating <- factor(mry$rating) 
p <- ggplot(mry, aes(x=year, y=number, group=rating)) 
p <- p + geom_line() 
p <- p + geom_point(data=mry[!(mry$rating %in% tmp.data),], 
        aes(x=year, y=number, group=rating, color=rating), size=2) 
p <- p + scale_color_brewer() 
p 

g2

11

Questo è stato fatto usando ggplot2 2.1.0. Penso che tu possa fare esattamente ciò che l'OP desidera, semplicemente passando la parentesi in modo che comprenda l'intera istruzione if.

Ecco un esempio che aggiunge una linea orizzontale a seconda se Swtich è T o F. In primo luogo, in cui la condizione è 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() 

enter image description here

Ora, la stessa cosa ma la condizione è 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() 

enter image description here

+0

sembra che non si possa usare il '+' all'interno di '{', quindi se si vogliono aggiungere condizionatamente più cose a un ggplot, credo che sia necessario aggiungere un'altra istruzione 'if' (all'interno della propria' {') per ogni oggetto che aggiungi alla trama. – filups21