wraymond
wraymond

Reputation: 325

Plot with two y axes with different x range

As written now this produced a plot with both data sets on two y axes but does not reflect the difference in x range. y2 only has an x range of 1988 to 2014 and y1 has a range from 1969 to 2014. How do I fix this?

df1<-data.frame(Year=c(1969,1975,1983,1988,1994,2003,2011),y1=c(412,700,1625,4521,8180,10563,25712))
df2<-data.frame(Year=c(1988:2014), y2=c(55,141,82,75,364,771,312,191,120,273,330,291,343,321,313,339,264,312,295,429,217,548,535,654,863,1379,1025))
par(mar= c(5,4,4,4))
plot(y1 ~ Year, data = df1, xlim=c(1969,2020), pch = 16, cex = 1.2, xlab = "year", ylab = "")
axis(2, ylim = c(0,27000))
mtext("y1", side = 2, line = 2.5)
par(new = T)
plot(y2 ~ Year, data = df2, pch = 1, cex = 1.2, xlab = "", ylab = "", axes = F, xlim = c(1988, 2014))
mtext("y2", side = 4, line = 2.5)
axis(4, ylim = c(0, 1500))

The range for years of df2 should only be form 1988 to 2014 but how its plotted it looks like it for the whole range.

Upvotes: 0

Views: 188

Answers (1)

JACKY88
JACKY88

Reputation: 3557

You could use twoord.plot function in plotrix package.

library(plotrix)
twoord.plot(df1$Year, df1$y1, df2$Year, df2$y2, xlab="Year", lylim = range(df1$y1) + c(-1000, 1000), rylim = range(df2$y2) + c(-100, 100), type = "o", ylab = "y1", rylab = "y2")

enter image description here

Upvotes: 1

Related Questions