0

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:

The rearranged figures

But if I do it individually, it should be:

The individual figure

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))
Z.Lin
  • 28,055
  • 6
  • 54
  • 94
Hong
  • 49
  • 6
  • 1
    Please share a sample of your data using `dput()` (not `str` or `head` or picture/screenshot) so others can help. See more here https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example?rq=1 – Tung Oct 04 '18 at 21:29
  • 1
    Can you make your example reproducible by adding in your plots and the code you used for combining plots? You can keep the plots simple (no need for themes, etc.); they just need to demonstrate the problem so folks can help troubleshoot. I'm wondering if this has something to do with `scaleFactor` (if you name this the same thing for each plot). – aosmith Oct 04 '18 at 22:48
  • I was looking at this again today and think it's very likely that `scaleFactor` is the culprit. Rather than using the same name for this for each plot, make objects with unique names (e.g., `scaleFactor1`, `scaleFactor2`). Alternatively skip making an object all together and put the calculation directly into `sec_axis()`. – aosmith Oct 05 '18 at 16:02
  • Yes, the problem is the scaleFactor. When I tried to name it with different names yesterday, the plot is correct. Thank you for your suggestions! @aosmith – Hong Oct 05 '18 at 17:29

0 Answers0