【问题标题】:How to draw ggplot of lm(log(y)~)and lm(y~x+x^2) in one plot如何在一个图中绘制 lm(log(y)~) 和 lm(y~x+x^2) 的 ggplot
【发布时间】:2016-04-14 18:14:52
【问题描述】:

使用包 ggplot2 和 iris,我想用拟合的回归线绘制散点图。

library(ggplot2)
ggplot(data=iris, aes(x = Petal.Width, y = Petal.Length,color=Species)) + 
  geom_point(shape=1) +
  stat_smooth(method = "lm",formula= 'Petal.Length ~ Petal.Width+I(Petal.Width^2)+SaleType+Petal.Width*Species', data=iris,
              aes(x = Petal.Width, y = Petal.Length,color=Species))

**Warning message:
Computation failed in `stat_smooth()`:
variable lengths differ (found for '(weights)')** 

我正在考虑收到此警告的原因,即我有两个自变量,但现在 R 无法读取 stat_smooth 中按颜色划分的物种。如何绘制两条与plot(Petal.Width,fitted(fit)) 相同的线。另外,如果我有另一个回归模型由同一组数据拟合,但是log(y),fit<-lm(log(Petal.Length)~Petal.Width+Species+Petal.Width*Species,data=iris).我可以把两个回归模型的绘制放到同一个图中吗?

【问题讨论】:

    标签: r plot ggplot2 regression scatter-plot


    【解决方案1】:

    我认为将转换后的回归与相同比例的原始值结合起来并不合适。相反,这些应该绘制在不同的数字上。使用iris 数据集,您可以像这样绘制原始数据:

    ggplot(data=iris, aes(color=Species)) + 
      geom_point(aes(x = Petal.Width, y = Sepal.Width)) +
      stat_smooth(method = "lm", aes(x = Petal.Width, y = Sepal.Width,color=Species))
    

    然后记录转换Sepal.Width到另一个变量:

    iris$LogSepal.Width <- log(iris$Sepal.Width)
    

    然后绘制转换后的变量。我希望这会有所帮助。

    ggplot(data=iris, aes(color=Species)) + 
      geom_point(aes(x = Petal.Width, y = LogSepal.Width)) +
      stat_smooth(method = "lm", aes(x = Petal.Width, y = LogSepal.Width,color=Species))
    

    【讨论】:

    • 谢谢!我知道你做日志的想法。但是如何绘制变量二次方的回归拟合线以及交互作用。
    • 我明白了。通常最好在 ggplot2 之外运行您的模型(如果它们有任何复杂性)。所以我会像平常一样运行它,然后绘制模型结果。
    猜你喜欢
    • 1970-01-01
    • 2015-11-20
    • 2017-06-18
    • 2012-05-06
    • 2018-04-17
    • 1970-01-01
    • 2021-01-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多