Arch Desai
Arch Desai

Reputation: 331

How to initialize ylim in ggplot?

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.

Upvotes: 0

Views: 119

Answers (1)

Arch Desai
Arch Desai

Reputation: 331

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

Upvotes: 1

Related Questions