I’m working on exporting plots in R, and I need to dynamically set the dimensions (height and width) of the exported plot based on the plot’s aspect ratio. The plots may have different scales on the x and y axes. How can I achieve this dynamically for both ggplot2 and base R graphics?
For example, if I have a plot p created with ggplot2 or plot() in base R, how can I determine the appropriate dimensions for the exported file (png, jpeg, etc.) so that the plot retains its aspect ratio and part are not cut off during export?
I am currently developing an R package and aim to include functionality for exporting plots generated by the package without requiring users to manually adjust the height and width settings.
so instead of:
ggsave("plot.png", plot = p, width = 8, height = 6)
I want the width and height be calculated based on the plot (p) object. Is that possible?
Any help or guidance would be greatly appreciated. Thank you!
I tried calculating the range difference between x and y axis by extracting the information from the plot object. that doesnt work since the scale is not the same between different plot objects with different data sets used
# Calculate dynamic dimensions based on the data ranges or other metrics
x_range <- diff(range(plot_data$layout$panel_params[[1]]$x.range))
y_range <- diff(range(plot_data$layout$panel_params[[1]]$y.range))
# Set dimensions with a scaling factor
scale_factor <- 1 # Adjust as needed
plot_width <- x_range * scale_factor
plot_height <- y_range * scale_factor