我对 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 :
但是,第二次拟合不起作用:
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))*
给我:
它通过曲线连接我拥有的 12 个数据值。
然后我对数据进行了排序,以便链接 12 个值的线将连续
add_trace(x=sort(score), y=fitted(qfit2)[order(score)],
type="scatter", mode="lines",
line=list(shape="spline", smoothing=1.3))*
但结果又不是我想要的:
生成的线一点也不平滑,它基本上将 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)
这条线不太平滑,因为拟合点很少。要使线条更平滑,请创建新数据:
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)
来自评论的数据:
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)
问题是您的拟合值稀疏且不均匀,因此您需要预测均匀分布的新数据以获得漂亮的曲线。
关于r - 使用 R plotly 的二次回归线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49490886/