As mentioned here: https://gist.github.com/tomhopper/9076152#gistcomment-2624958 there is a difference between the two options:
#get ranges of the data
ggplot_build(obj)$layout$panel_scales_x[[1]]$range$range
ggplot_build(obj)$layout$panel_scales_y[[1]]$range$range
#get ranges of the plot axis
ggplot_build(obj)$layout$panel_params[[1]]$x.range
ggplot_build(obj)$layout$panel_params[[1]]$y.range
Here is a set of convenience functions to take a list of plots, extract the common y-axis range and replace it. I needed it because I used different data sets within one graph arranged via ggarange
:
require(ggplot2)
get_plot_view_ylimits <- function(plot) {
gb = ggplot_build(plot)
ymin = gb$layout$panel_params[[1]]$y.range[1]
ymax = gb$layout$panel_params[[1]]$y.range[2]
message(paste("limits are:",ymin,ymax))
list(ymin = ymin, ymax = ymax)
}
change_plot_ylimits <- function(plot, nlimits){
p <- plot + ggplot2:::limits(unlist(nlimits, use.names =FALSE),"y")
}
adjust_plots_shared_ylimits <- function(plotList) {
first <- TRUE
for (plot in plotList) {
if (first) {
nlimits <- get_plot_view_ylimits(plot)
first <- FALSE
} else {
altLimits <- get_plot_view_ylimits(plot)
nlimits$ymin <- min(nlimits$ymin,altLimits$ymin)
nlimits$ymax <- max(nlimits$ymax,altLimits$ymax)
}
}
message(paste("new limits are:",nlimits$ymin,nlimits$ymax))
lapply(plotList,change_plot_ylimits,nlimits)
}
I thought this might also be useful for others.
expand
. See here. – joranexpand
argument to thescale_*
functions inggplot
. For example, see the defaults listed here. – joranggplot_build(obj)$layout$panel_scales_x[[1]]$range$range
ggplot_build(obj)$layout$panel_scales_y[[1]]$range$range
– Michael