【问题标题】:How can I make a linear relation between two vectors?如何在两个向量之间建立线性关系?
【发布时间】:2018-07-13 23:07:56
【问题描述】:

我正在尝试用 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) 

我得到一个错误。

【问题讨论】:

    标签: r plot plotly r-plotly


    【解决方案1】:

    你可以试试这个:

    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)
    

    【讨论】:

    • 警告信息:1:数字颜色变量(还)不能映射到行。当跟踪类型为“scatter”或“scattergl”时。 2:plotly.js 还不支持 line.width 数组,跟踪这个问题的进展
    • 我明白你的意思。有没有可能放弃外推?极端值?不管你知道与否,我都会接受你的回答
    • 查看编辑。您可以为大于 0 的值创建一个新的数据集和子集
    • 不不,看看你的台词,它带有截距。我想通过0,不截取并计算相关性,你知道我的意思吗?
    • 这对我有用: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 = fit(fit), name = "回归线", showlegend=FALSE) %>% layout(注释 = a)