I plot three figures by ggplot2 and I like to rearrange them to one page. Each figure has dual Y axes, and these figures have different second Y-axis scaling. If I use grid.arrange or something function like that, it will lead to a missing value in my first and second figure, which will actually use the second Y-axis scale of the third figure. It is like this:
But if I do it individually, it should be:
The code is like this:
scaleFactor <- max(sum_PDSI$PDSI_1) / max(sum_PDSI$Yield_1)
plot1 <- ggplot(sum_PDSI,aes(Year)) +
geom_line(aes(y=PDSI_1),color = "BLUE", size = 0.8) +
geom_line(aes(y=Yield_1 * scaleFactor),color = "RED", size = 0.8) +
scale_y_continuous(name="PDSI", limits = c(-8, 6),
sec.axis=sec_axis(~./scaleFactor, name="Yield (BU/Acre)")) +
theme_set(theme_grey()) +
theme(axis.title.y.left=element_text(color="blue"),
axis.text.y.left=element_text(color="blue"),
axis.title.y.right=element_text(color="red"),
axis.text.y.right=element_text(color="red")) +
theme(axis.title.x = element_blank()) +
annotate("text", x = 1982, y = 5, hjust = 0, size = 4,
label = "R = 0.46 P < 0.01")
plot1
The data are:
sum_PDSI = data.frame(Year = 1981:2016,
PDSI_1 = runif(36, -4, 4),
PDSI_2 = runif(36, -4, 4),
PDSI_3 = runif(36, -4, 4),
Yield_1 = runif(36, -40, 80),
Yield_2 = runif(36, -1000, 1000),
Yield_3 = runif(36, -10, 20))