r - 使用 R plotly 的二次回归线

标签 r regression plotly quadratic r-plotly

我对 R 很陌生,对 plotly 真的很陌生。 .

我正在尝试绘制二次(即二阶多项式)回归线。
一旦某些价格与年份,以及相同的价格与某些整数列表(可以相同),我们就说分数。
本例中的数据为

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"),)

产生这个 plotly :

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,但这给了我更糟糕的结果)

非常感谢您提前。

最佳答案

这是一个用于绘制拟合模型的工作代码:

  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

问题是您的拟合值稀疏且不均匀,因此您需要预测均匀分布的新数据以获得漂亮的曲线。

关于r - 使用 R plotly 的二次回归线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49490886/

相关文章:

python - sklearn.feature_selection 的 F_Regression

python - 如何使用 google collaboratory 在输出中显示 Plotly slider ?

R - 矢量化条件替换

R 跟踪在函数内部无法正常工作?

r - 在线性回归中使用数据框的列名称作为预测变量

python - 使绘图中的 X 轴更宽,Y 轴更窄

python - 如何使用电子表格中的两个不同列制作分组条形图?

r - 保存多个箱线图

r - dplyr排列-按另一列对组进行排序,然后在每个组内进行排序

java - 多维多项式回归(最好是 C/C++、Java 或 Scala)