0

I am trying to make a function to plot various variables. I want to initialize ylim in a function such that if I provide ylim, then only it is taken into consideration otherwise not. I can achieve this by if statement but I want to see if there are any other better options?

# function to plot variables turbine wise
plot_fun <- function(df, x_var, y_var, plot_title = "", ncol = 3, ylim = NA){
  g <- list()

  for(i in 1:length(unique(df$turbine_id))){
    temp_df <- subset(df, turbine_id == unique(df$turbine_id)[i])
    comp.manufact <- temp_df$comp.manufact[1]

    g[[i]] <- ggplot(temp_df, aes_string(x = x_var, y = y_var)) + 
                geom_point(size = 0.5, color = ifelse(comp.manufact == "Winergy", "darkgreen", "black")) + 
                ggtitle(paste("Turbine", unique(temp_df$turbine_id))) +
                theme(axis.title = element_blank()) + 
                ylim
  }

  grid.arrange(grobs = g, ncol = ncol, top = plot_title, left = y_var, bottom = x_var)
}

If I provide ylim, it should consider it otherwise not.

Thank you.

Richard Telford
  • 9,558
  • 6
  • 38
  • 51
Arch Desai
  • 191
  • 1
  • 8
  • you have to use `+ylim(minimum,maximum)` – dc37 Jan 02 '20 at 14:42
  • Then I will have to provide minimum and maximum all the time right? I would like to use a function like this. `plot_fun(df, "Day", "power")` and/or `plot_fun(df, "Day", "speed", ylim = c(0, 200)` – Arch Desai Jan 02 '20 at 14:44
  • 1
    You can pass limits to a scale function. Try to make this a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) to get more specific help – camille Jan 02 '20 at 15:09

1 Answers1

1

Found the solution. using the scale_y_continuous we can achieve that in ggplot2. Thank you all.

# function to plot variables turbine wise
plot_fun <- function(df, x_var, y_var, plot_title = "", ncol = 3, ylim = c(NA,NA)){
  g <- list()

  for(i in 1:length(unique(df$turbine_id))){
    temp_df <- subset(df, turbine_id == unique(df$turbine_id)[i])
    comp.manufact <- temp_df$comp.manufact[1]

    g[[i]] <- ggplot(temp_df, aes_string(x = x_var, y = y_var)) + geom_point(size = 0.5, color = ifelse(comp.manufact == "Winergy", "darkgreen", "black")) + ggtitle(paste("Turbine", unique(temp_df$turbine_id))) + theme(axis.title = element_blank()) + scale_y_continuous(limits = ylim)

  }
  grid.arrange(grobs = g, ncol = ncol, top = plot_title, left = y_var, bottom = x_var)
}
Arch Desai
  • 191
  • 1
  • 8