【问题标题】:R how to respectively add regression lines for two groups of points in two-y-axis plot using the plotrix packageR如何使用plotrix包分别为两个y轴图中的两组点添加回归线
【发布时间】:2018-03-05 01:48:36
【问题描述】:

我使用plotrix 包创建了一个两个y 轴图来显示两组点,下一步是分别为两组点添加回归线。但我不知道如何处理这种情况。有什么建议么?提前谢谢!

创建两个 y 轴图的示例代码:

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)

【问题讨论】:

    标签: r plotrix


    【解决方案1】:

    这是一个棘手的机器人问题,因为twoord.plot 的帮助表明对绘图的任何进一步添加都将相对于左侧纵坐标绘制:

    请注意,可以使用点或线将更多值添加到绘图中, 但请记住,这些将相对于左纵坐标绘制。

    但我认为可以通过一些缩放来完成。首先让我们将您的数据转换为数据框,以便我们可以拟合回归:

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

    第二个:

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

    现在由于 pred2 与 pred1 的比例完全不同,我们需要将其缩放到 pred1 的范围,可以使用 scales 中的 rescale。我填充定义了两个缩放范围:

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

    我还将使用这些范围作为rylimlylim 中的参数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")
    

    检查它是否与我们刚刚绘制 pred2 时相似:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-19
      • 1970-01-01
      • 1970-01-01
      • 2021-12-30
      • 1970-01-01
      相关资源
      最近更新 更多