Ask Your Question
0

How can I update the ylim in ggplot while using a loop?

asked 2022-05-06 11:00:00 +0000

lalupa gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-06-11 20:00:00 +0000

nofretete gravatar image

You can update the ylim in ggplot by using the ylim() function and specifying the minimum and maximum values of the y-axis. Here is an example using a loop to update the ylim for each plot:

library(ggplot2)

# Create sample data
df <- data.frame(x = 1:10,
                 y = c(3, 5, 6, 8, 9, 10, 7, 4, 2, 1))

# Create empty list to store plots
plot_list <- list()

# Loop over values to update ylim
for (i in 1:5) {

  # Calculate ylim based on maximum y value in data
  ylim_max <- max(df$y) + i

  # Create plot with updated ylim
  p <- ggplot(df, aes(x, y)) +
    geom_point() +
    ylim(0, ylim_max)

  # Add plot to list
  plot_list[[i]] <- p
}

# Print all plots in list
for (i in seq_along(plot_list)) {
  print(plot_list[[i]])
}

In this example, we first create some sample data (df) with x and y values. We then create an empty list plot_list to store our plots. We use a loop to update the ylim for each plot, and for each iteration we calculate the maximum value of y in the data (ylim_max) and add the iterator value to it. We then create a plot using ggplot with geom_point and ylim set to 0 and ylim_max. Finally, we add each plot to our plot_list and print all plots in the list using another loop.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-05-06 11:00:00 +0000

Seen: 9 times

Last updated: Jun 11 '22