Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if else condition in ggplot to add an extra layer

say I want to plot two layers in ggplot, one containing points and another one containing lines if a certain criteria is fulfilled.

The code without the criteria could look like this:

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

now the condition for plotting the points and not only the lines would be, that an object called tmp.data does not equal the expression "no value".

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

fails....

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

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

like image 805
joaoal Avatar asked Apr 07 '14 14:04

joaoal


People also ask

What does %>% do in Ggplot?

%>% is a pipe operator reexported from the magrittr package. Start by reading the vignette. Adding things to a ggplot changes the object that gets created. The print method of ggplot draws an appropriate plot depending upon the contents of the variable.

What does Geom_point () do in R?

The function geom_point() adds a layer of points to your plot, which creates a scatterplot.

How many layers are there in Ggplot?

There are three layers in this plot. A point layer, a line layer and a ribbon layer. Let us start by defining the first layer, point_layer . ggplot2 allows you to translate the layer exactly as you see it in terms of the constituent elements.

Which operator allows you to add objects to a Ggplot?

The + operator updates the elements of e1 that differ from elements specified (not NULL) in e2. Thus this operator can be used to incrementally add or modify attributes of a ggplot theme.


1 Answers

This was done using ggplot2 2.1.0. I think you can do exactly what the OP wished, just by switching the parenthesis so that they encompass the entire if statement.

Here is an example that add a horizontal line depending on if Swtich is T or F. First, where the condition is 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

Now, the same thing but the condition is 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

like image 102
John Paul Avatar answered Oct 02 '22 06:10

John Paul