0

Can someone help me plot two variables on one plot with two different scales. I want a plot like the one attached here.

enter image description here.

Here is my code, plotting NDVI and Rainfall. But I am getting an error:

Error in seq.default(range1, range[2], length.out = self$detail) : 'from' must be of length 1

 scaleFactor <- max(modis8$Precip) / max(modis8$NDVI)
 
 ggplot(modis8, aes(x=YEAR)) +
   geom_smooth(aes(y=precip), method="loess", col="blue") +
   geom_smooth(aes(y=NDVI * scaleFactor), method="loess", col="red") +
   scale_y_continuous(name="Precipitation", sec.axis=sec_axis(~./scaleFactor, name="NDVI")) +
   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"))

Thank you for your help.

Here is a snapshot of my data for reference from 2002 until 2020.

YEAR MONTH       DATE   ForestID     PlotType    EVI      NDVI Precip
1   2002     7 01/07/2002   Chobe001    lowforest 0.1893 0.2874659      0
2   2002     7 01/07/2002   Chobe002    lowforest 0.1798 0.2945573      0
3   2002     7 01/07/2002   Chobe003        grass 0.1674 0.2974389      0
4   2002     7 01/07/2002   Chobe004        grass 0.2903 0.3740139      0
5   2002     7 01/07/2002   Chobe005        grass 0.1938 0.2809047      0
6   2002     7 01/07/2002   Chobe006    lowforest 0.1694 0.3057424      0
7   2002     7 01/07/2002   Chobe007 mediumforest 0.1616 0.2741029      0
8   2002     7 01/07/2002   Chobe008       shrubs 0.1343 0.2307692      0
9   2002     7 01/07/2002   Chobe009        grass 0.1675 0.2522296      0
Werner Hertzog
  • 2,002
  • 3
  • 24
  • 36
LisaD
  • 41
  • 2
  • ggplot intentionally does not support multiple y-scales in the same plot, but suggests using facets instead. see https://stackoverflow.com/questions/6142944/how-can-i-plot-with-2-different-y-axes for details on how to accomplish this in base graphics – Brian Fisher Nov 20 '20 at 17:24
  • Thank you for your reply, I will try the facets and see if it works – LisaD Nov 21 '20 at 17:36

0 Answers0