如何在两个向量之间建立线性关系?
How can I make a linear relation between two vectors?
我正在尝试用 plot_ly
制作相关图
我举个例子
library(plotly)
d <- diamonds[sample(nrow(diamonds), 1000), ]
p <- plot_ly(
d, x = ~carat, y = ~price,
# Hover text:
text = ~paste("Price: ", price, '$<br>Cut:', cut),
color = ~carat, size = ~carat
)
然后绘制
但是我怎样才能画出直线并计算出R2呢?
有办法吗?
如果您知道任何其他方法,请告诉我。
例如,像这样的东西会很棒
[![enter image description here][1]][1]
http://vault.hanover.edu/~altermattw/courses/220/R/corr/corr_2.html
我尝试使用:
library(ggplot2)
ggplot(d, aes(x=carat, y=price)) +
geom_point(aes(colour = Outcome)) +
geom_smooth(method=lm)
我遇到了一个错误。
你可以试试这个:
fit <- lm(price ~ carat-1, data = d)
summary(fit)$adj.r.squared
a <- list(
x = 2,
y = 5000,
text = "R2 = 0.88",
xref = "x",
yref = "y",
showarrow = FALSE,
arrowhead = 7
)
plot_ly() %>% add_markers(data = d, x= ~ carat, y = ~ price, color = ~carat, size = ~carat, name = "Size", marker=list(colorbar=list(title='Colorbar'))) %>%
add_lines(x = ~carat, y = fitted(fit), name = "Regression line") %>%
layout(annotations = a)
我正在尝试用 plot_ly
制作相关图我举个例子
library(plotly)
d <- diamonds[sample(nrow(diamonds), 1000), ]
p <- plot_ly(
d, x = ~carat, y = ~price,
# Hover text:
text = ~paste("Price: ", price, '$<br>Cut:', cut),
color = ~carat, size = ~carat
)
然后绘制
但是我怎样才能画出直线并计算出R2呢? 有办法吗?
如果您知道任何其他方法,请告诉我。
例如,像这样的东西会很棒
[![enter image description here][1]][1]
http://vault.hanover.edu/~altermattw/courses/220/R/corr/corr_2.html
我尝试使用:
library(ggplot2)
ggplot(d, aes(x=carat, y=price)) +
geom_point(aes(colour = Outcome)) +
geom_smooth(method=lm)
我遇到了一个错误。
你可以试试这个:
fit <- lm(price ~ carat-1, data = d)
summary(fit)$adj.r.squared
a <- list(
x = 2,
y = 5000,
text = "R2 = 0.88",
xref = "x",
yref = "y",
showarrow = FALSE,
arrowhead = 7
)
plot_ly() %>% add_markers(data = d, x= ~ carat, y = ~ price, color = ~carat, size = ~carat, name = "Size", marker=list(colorbar=list(title='Colorbar'))) %>%
add_lines(x = ~carat, y = fitted(fit), name = "Regression line") %>%
layout(annotations = a)