0

The first y axis is distorted when plotting the second y axis, see below:

Treatment<-c("T1-Control", "T1-Control", "T1-Control", "T1-Control", "T1-Control",
             "T1-Inseticide", "T1-Inseticide", "T1-Inseticide", "T1-Inseticide", "T1-Inseticide",
             "T2-Control", "T2-Control", "T2-Control", "T2-Control", "T2-Control",
             "T2-Inseticide", "T2-Inseticide", "T2-Inseticide", "T2-Inseticide", "T2-Inseticide")
Measurement<-rep(c(1, 2, 3, 4, 5), 4)
Infestation<-c(12, 8, 9, 4, 5, 1, 0, 0, 2, 1, 18, 11, 28, 9, 15, 0, 2, 1, 0, 2)
Rainfall<-rep(c(56.8, 236.1, 71, 259, 145), 4)
d<-data.frame(cbind(Treatment, Measurement, Infestation, Rainfall))
i<-c(2,3,4)
d[,i]<-apply(d[,i],2,function(x) as.numeric(as.character(x)))

max(d$Rainfall)/max(d$Infestation)

library(ggplot2)
p<-ggplot(d, aes(x= Measurement,y=Infestation,linetype = factor(Treatment))) +
       geom_point(mapping=aes(x= Measurement, y=Infestation, shape = factor(Treatment))) +
       geom_line(mapping=aes(x= Measurement, y=Infestation, linetype = factor(Treatment)), size=0.3) +
       geom_line(aes(y= Rainfall))+
       scale_y_continuous(name="Infestation", sec.axis = sec_axis(~9.25*., name=" Rainfall "))
p

Result with distorted first y axis

The black lines between 0 and 28 are the result of insect infestation according to treatments (4). The blue line represents the rainfall over the period evaluated. The dimensions of the axes are different. I need to fix the second y-axis scale without distorted de first. This is a small sample of the database. I need the second y-axis limits between zero and 260.

How I can fix it? Please, any ideas?

Isabel
  • 323
  • 1
  • 11
  • 2
    Make this adjustment `geom_line(aes(y= Rainfall/9.25))` for the scale to match. the 9.25 is the scaling factor you used to define the secondary axis. For ggplot "All secondary axes must be based on a one-to-one transformation of the primary axes." – Dave2e Aug 27 '19 at 20:40
  • Thanks Dave2e. Problem solved! – Isabel Aug 27 '19 at 20:46
  • Just for the record that it's actually discouraged and why: https://stackoverflow.com/a/3101876/5795592 – hannes101 Sep 03 '19 at 06:31

0 Answers0