I want to perform a chart that involves two variables (weight - kg) and (rain - mm) through the years (1991 - 2021). BOTH VARIABLES ARE NOT RELATED!
Everything goes ok when plotting the graphs separated one from each other:
library(ggplot2)
ggplot(data2, aes(x=ano_dtt)) +
geom_col(aes(y=PesoAj220_d), fill="lightblue2") +
ylim(0,300)
ggplot(data2, aes(x=ano_dtt)) +
geom_point(aes(y=ppt)) +
geom_path(aes(y=ppt)) +
ylim(0,1700)
But, when I try to add the second axis everything goes wrong!!!
scaleRight <- 0.75
ggplot(data2, aes(x=ano_dtt)) +
geom_col(aes(y=PesoAj220_d), fill="lightblue2") +
ylim(0,300) +
geom_point(aes(y=ppt)) +
geom_path(aes(y=ppt), colour="red", size=0.9) +
ylim(0,1700)+
scale_y_continuous(sec.axis = sec_axis(~.*scaleRight, name="precipitacion (mm)")) +
labs(title = "", x="año", y="peso")
I also try this:
scaleRight <- 0.75
ggplot(data2, aes(x=ano_dtt)) +
geom_col(aes(y=PesoAj220_d), fill="lightblue2") +
ylim(0,300) +
geom_point(aes(y=ppt)) +
geom_path(aes(y=ppt), size=0.9) +
ylim(c(0,1700))
But there is something wrong with the only axis present in the plot.
I think that the problem is with the
scaleRight <- 0.75
Can someone help to solve this problem? I'm pretty sure that is very very easy!




The issue you face is that you have to scale your secondary y-axis values to fall within the range of the primary x-axis. As you guessed, multiplying the secondary y-axis values by a set value (scaleRight) is not how to achieve your goal.
I struggle with scaling within a
sec_axis()function, so I prefer to scale the secondary y-axis values prior to plotting. The approach outlined below creates the same number of axis breaks on both y-axes, comment if you prefer a different number of breaks each side and I'll update the code.