I'm trying to set the minimum y value for a dual axis chart. I understand having dual axis is not entirely best practices when plotting, but this is a requested item. I'd like to try and have the minimum set to anything above zero.
Looking online I have not found an answer other than adjusting or using expansion
. The issue with this is, since it contracts, anything not in the area gets cut off. The plot was made using tenubrand's answer here.
ggplot with 2 y axes on each side and different scales
I thought his use of y max values in his post could be changed to min but it didn't work. So I included expansion, but it's not dynamic and doesn't work well for varying data sets. Some graphs even cut of at some points.
library(scales)
library(ggplot2)
# Function factory for secondary axis transforms
train_sec <- function(primary, secondary, na.rm = TRUE) {
from <- range(secondary, na.rm = na.rm)
to <- range(primary, na.rm = na.rm)
forward <- function(x) {
rescale(x, from = from, to = to)
}
reverse <- function(x) {
rescale(x, from = to, to = from)
}
list(fwd = forward, rev = reverse)
}
sec <- with(economics, train_sec(unemploy, psavert))
ggplot(economics, aes(date)) +
geom_col(aes(y = unemploy), colour = "blue") +
geom_line(aes(y = sec$fwd(psavert)), colour = "red") +
scale_y_continuous(name = NULL,
expand = expansion(mult = c(-.2, .1)),
sec.axis = sec_axis(~sec$rev(.), name = "psavert"))