I have a ggplot2 barplot with multiple facets, and would like to superimpose a line plot with a different Y axis on each of the facets. The issue I'm facing is that the relationship between the primary and secondary Y axes is different for each facet. Is there any way to make the secondary axis scale to the line plot data so the full height of the plot is used in each facet?
Here's a minimal example, ideally the left axis should have range (0, 30) in both facets, but the right axes would have ranges (0, 130) and (0, 10):
library(ggplot2)
temp <- data.frame(
region = c("1", "1", "1", "1", "1", "2", "2", "2", "2", "2"),
year = c(2010, 2011, 2012, 2013, 2014, 2010, 2011, 2012, 2013, 2014),
temp = c(22, 23, 20, 17, 26, 21, 28, 19, 17, 22)
)
wind <- data.frame(
region = c("1", "1", "1", "1", "1", "2", "2", "2", "2", "2"),
year = c(2010, 2011, 2012, 2013, 2014, 2010, 2011, 2012, 2013, 2014),
wind = c(112, 125, 124, 119, 108, 7, 3, 8, 5, 2)
)
ggplot() +
geom_bar(data = temp, aes(year, temp, fill = region), stat = "identity") +
geom_line(data = wind, aes(year, wind)) +
facet_wrap(~region, nrow = 2, scales = "free") +
scale_y_continuous(sec.axis = sec_axis(~., name = "wind"))