How to create a graph with two axes and with different scales in R?

1

I'm trying to plot a chart with 3 datasets. "Precipitation" and "Evapotranspiration" have high values (from 5 to 580) so it would use the same Y-scale (from the shale side) for both plotted data superimposed on line graph. The data of "Days with rain" (ranging from 3 to 28), I want to plot in the same graph but with a scale in own Y (of the right side).

I tried:

plot(etp,type="l",ylim=c(5,580),col="turquoise",ylab="pluviosidade",xlab="mês)
lines(prec,col="turquoise3")
abline(v=seq(1,121,12),lty=2, col="gray")
lines(dcch,type="l",lwd="2",mar=c(5,4,2,5),ylim=c(3,28),col="darkorchid3",ylab="dias com chuva",xlab="mês")
axis(side=4,ylim=c(3,28),line=3,ylab="dias com chuva")

And I also tried:

plot(etp,type="l",ylim=c(5,580),col="turquoise",ylab="pluviosidade",xlab="mês")
lines(prec,col="turquoise3")
lines(dcch,type="l",lwd="2",col="darkorchid3")
abline(v=seq(1,121,12),lty=2, col="gray")
par(new=TRUE)
axis(side=2,ylim=c(5,580))
axis(side=4,ylim=c(0,30))

Where is the error?

    
asked by anonymous 01.11.2017 / 14:16

1 answer

4

The error is probably attempting to plot "Rainy Days" before par(new = TRUE) . Also, after par(new = TRUE) you have to create a new plot() to plot lines with lines() .

I tried to change your code without your data, but as Rafael Cunha pointed out, it's important that in the next few questions you always provide some of the data to make the example reproducible.

par(mar = c(4, 4, 1, 4)) # aumentar a margem do gráfico no lado direto
plot(etp, type = "l", ylim = c(5, 580), col = "turquoise", ylab = "pluviosidade", xlab = "mês")
lines(prec, col = "turquoise3")
abline(v = seq(1, 121, 12), lty = 2, col = "gray")
par(new = TRUE) # adicionar nova janela gráfica sobre a janela interior
plot(etp, pch = "", ylim = c(0, 30), yaxt = "n", ylab = "", xlab = "") # plotar gráfico sem informações
lines(dcch, type = "l", lwd = "2", col = "darkorchid3")
axis(side = 4, ylim = c(0, 30)) 
mtext("Dias com chuva", side = 4, line = 3)
    
01.11.2017 / 20:10