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

Asked

Viewed 1,006 times

1

I’m trying to plot a graph with 3 sets of data. " Precipitation" and "Evapotranspiration" have high values (from 5 to 580) so would use the same scale in Y (on the left side) for both plotted data superimposed on line graph. The data of "Rainy days" (ranging from 3 to 28), I want to plot in the same graph but with a proper Y scale (on the right side).

I tried to:

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 tried too:

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?

  • 2

    make your data set, or a part of it, available with the command dput for your problem to be reproducible

1 answer

4


The error is probably in trying to plot "Rainy days" before par(new = TRUE). In addition, after par(new = TRUE) you have to create a new plot() to then plot lines with the lines().

I tried to modify your code without your data, but as Rafael Cunha pointed out, it is important that in the next questions you always provide a piece of 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)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.