This is one application from my earlier post on similar subject - Clubbing 2 ggplots in a single windows and putting 2nd one in Secondary axis
Let say I have below ggplot
, and I want to have secondary axis for the variable y2
library(ggplot2)
library(quantmod)
dat = data.frame(x = as.yearqtr(seq(as.Date('2002-01-01'), length.out = 17, by = '95 day')),
y1 = c(-0.0042, 0.0221, 0.0387, 0.0523, -0.0743, -0.0903, 0.0997, 0.0982, 0.0956, -0.0961, -0.0696, -0.0818, 0.0766, 0.0654, 0.1275, 0.1178, 0.0878),
y2 = c(19747, 19343, 19007, 18336, 17534, 16548, 15536, 14400, 13428, 12686, 11877, 11250, 10625, 10122, 9740, 9314, 8892))
ggplot(dat, aes(x = x)) +
geom_col(aes(y = (y2 - 14000) / 8000), fill = 'red') +
geom_line(aes(y = y1, colour = 'TempMax'), size = 1.2) +
scale_y_continuous(name = 'Temp', limits = c(-3, 3),
sec.axis = sec_axis(~(.x * 8000 + 14000), name = 'var'))
With this I am getting below plot
This plot looks strange to me. Why my bars for y2
going to negative territory?
I also tried with changing the transformation as,
ggplot(dat, aes(x = x)) +
geom_col(aes(y = (y2 - 8000) / 8000), fill = 'red') +
geom_line(aes(y = y1, colour = 'TempMax'), size = 1.2) +
scale_y_continuous(name = 'Temp', limits = c(-3, 3),
sec.axis = sec_axis(~(.x * 8000 + 8000), name = 'var'))
With this, I get below plot
As you see, the range for secondary y axis
still going into negative zone. I would ideally expect to see limit of secondary y axis
starting from 0. Any idea on how can I make this correction will be very helpful.