0

I have created a two-y-axis plot to display two groups of points using the plotrix package, and the next step is to add regression lines for the two groups of points, respectively. But I have no idea how to handle this situation. Any suggestions? Thank you in advance!

Example code to create two-y-axis plot:

library(plotrix)

xval1 <- seq.Date(as.Date("2017-01-02"),
                  as.Date("2017-01-10"), by="day")
xval2 <- seq.Date(as.Date("2017-01-01"),
                  as.Date("2017-01-15"), by="day")
going_up <- seq(3,7,by=0.5)+rnorm(9)
going_down <- rev(60:74)+rnorm(15)
twoord.plot(2:10, going_up,1:15, going_down, xlab="Sequence", type = 'p',
            ylab = "Ascending values",rylab="Descending values",lcol=4)
just_rookie
  • 873
  • 12
  • 33

1 Answers1

1

This is a bot tricky since the help for twoord.plot suggests any further additions to the plot will be plotted relative to the left ordinate:

Note that more values can be added to the plot using points or lines, but remember that these will be plotted relative to the left ordinate.

But I think it can be done by a bit of scaling. First lets convert your data to data frames so we can fit a regression:

df1 <- data.frame(y = going_up, x = 2:10)
res1 <- lm(y ~ x, df1) #fit
pred1 <- predict(res1, df1) #generate point for plotting

and for the second one:

df2 <- data.frame(y = going_down, x = 1:15)
res2 <- lm(y ~ x, df2)
pred2 <- predict(res2, df2)

now since pred2 is on a totally different scale than pred1 we need to scale it to the range of pred1, rescale from scales can be used. I fill define both scaling ranges:

pred2 <- scales::rescale(pred2, to = c(2, 8), from = c(58, 76))

I will use these ranges also as arguments rylim and lylim in twoord.plot:

twoord.plot(2:10, going_up, 1:15, going_down, xlab = "Sequence", type = 'p',
            ylab = "Ascending values", rylab = "Descending values", lcol = 4, rylim = c(58, 76), lylim = c(2, 8))
lines(2:10, pred1, col = "blue")
lines(1:15, pred2, col = "red")

enter image description here

Check if it looks similar to when we plot just pred2:

pred2 <- predict(res2, df2)
plot(1:15, going_down)
lines(1:15, pred2)

enter image description here

missuse
  • 19,056
  • 3
  • 25
  • 47