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.
Asked: 2022-05-06 11:00:00 +0000
Seen: 10 times
Last updated: Jun 11 '22