使用R plotly绘制二次回归线

4

我对R和plotly都很陌生。

我试图绘制一个二次(即2次多项式)回归线。 一次是价格与年份的关系,另一次是相同的价格与某些整数列表(可能相同),比如得分。 这个例子中的数据为:

price = c(995, 675, 690, 600, 612, 700, 589, 532, 448, 512, 537, 560)
score = c(89, 91, 88, 89, 91, 91, 89, 93, 83, 91, 91, 90)
year = c(2005:2016)

第一个适合编码的方法效果很好

enter code here
qfit1 <- lm(price ~ poly (year,2))

然后一个带有Plotly的图表

add_trace(x=year, y=fitted(qfit1), type="scatter", 
          mode="lines", line=list(shape="spline"),)

生成这个图表:

enter image description here

然而,第二个匹配不起作用:
qfit2 <- lm(price ~ poly (score,2))
p <- plot_ly() %>% ...
  add_trace(x=score, y=fitted(qfit2), type="scatter", mode="lines", 
  line=list(shape="spline", smoothing=1.3))*

给我:

enter image description here

这个程序将12个数据值通过曲线连接起来。然后我对数据进行了排序,以使连接12个值的曲线是连续的。

add_trace(x=sort(score), y=fitted(qfit2)[order(score)], 
          type="scatter", mode="lines", 
          line=list(shape="spline", smoothing=1.3))*

但是结果仍然不是我想要的:

enter image description here

生成的线条非常不平滑,基本上是用曲线将12个值连接起来。我注意到(当然我使用不同的数据生成了更多类似的图表),当某个分数(x轴)有不同的价格时,问题总是会发生。然而,我不知道如何解决这个问题。有任何想法吗?或者是否有其他方法使用R和plotly生成二次拟合线?(我也尝试过使用add_lines而不是add_trace,但结果更糟糕了)。
非常感谢您的帮助。

你能提供与代码相对应的数据吗?最好使用dput,并将其粘贴到你的问题中。 - missuse
对于这个特定的例子,我有:price = c(995, 675, 690, 600, 612, 700, 589, 532, 448, 512, 537, 560),score = c(89, 91, 88, 89, 91, 91, 89, 93, 83, 91, 91, 90) 和 year = c(2005:2016)。这有帮助吗? - Giannis K
1
谢谢,已添加答案,请检查一下。您能否通过“编辑”将那些数据放到您的原始帖子中呢? - missuse
2个回答

3
这里有一个能够在Plotly中绘制拟合模型的可用代码:
  library(plotly)
  library(dplyr)
  data(cars, package = "datasets")

 qfit1 <- lm(dist ~ poly(speed,2), data = cars)

  cars %>%     
  plot_ly() %>%  
  add_lines(x = ~speed, y = fitted(qfit1)) %>%
  add_trace(x=~speed, y=~dist)

enter image description here

由于拟合点较少,导致曲线不够平滑。为了让曲线更加平滑,请创建新数据:

  dat <- data.frame(speed = (1:300)/10,
                    dist = predict(qfit1, data.frame(speed = (1:300)/10)))
  plot_ly() %>% 
      add_trace(x=~speed, y=~dist, type="scatter", mode="lines", data = dat) %>%
      add_trace(x=~speed, y=~dist, type="scatter", data = cars)

enter image description here

使用评论中的数据:

 dat1 = data.frame(
       price = c(995, 675, 690, 600, 612, 700, 589, 532, 448, 512, 537, 560),
       score = c(89, 91, 88, 89, 91, 91, 89, 93, 83, 91, 91, 90))

qfit2 <- lm(price ~ poly (score,2), data = dat1)

  dat3 <- data.frame(score = (800:950)/10,
                    price = predict(qfit2, data.frame(score = (800:950)/10)))

plot_ly() %>% 
   add_trace(x=~score, y=~price, type="scatter", mode="lines", data = dat3) %>%
   add_trace(x=~score, y=~price, type="scatter", data = dat1)

enter image description here

问题在于您的拟合值稀疏且不均匀,因此需要在均匀间隔的新数据上进行预测,以获得漂亮的曲线。

0

你也可以使用ggplot2ggplotly来得到你想要的结果。试试这个:

library(plotly)
library(ggplot2)
data_df <- data.frame(price, score, year)
p <- ggplot(data_df, aes(x=score, y=price)) + 
  geom_point() + 
  geom_smooth(method="lm", se=FALSE, fill=NA, formula=y ~ poly(x, 2, raw=TRUE),colour="blue") + 
  theme_bw() 
ggplotly(p)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接