R 用plotly重画ggplot图

R 用plotly重画ggplot图,r,ggplot2,plotly,R,Ggplot2,Plotly,出于好奇,我正试图用plotly重建ggplot图 这是一个简单线性回归的例子。图表显示了观测数据,回归线和垂直线显示了误差 ggplot如下所示: 重建的plotly图形如下所示: 有没有办法将显示错误的垂直线推到点的后面 有更好的方法吗 数据可在此处找到: 这是用于绘制图的代码: library(ggplot2) library(plotly) #### prepare data #### adv <- read.csv("Advertisin

出于好奇,我正试图用plotly重建ggplot图

这是一个简单线性回归的例子。图表显示了观测数据,回归线和垂直线显示了误差

ggplot如下所示:

重建的plotly图形如下所示:

  • 有没有办法将显示错误的垂直线推到点的后面
  • 有更好的方法吗
  • 数据可在此处找到:

    这是用于绘制图的代码:

        library(ggplot2)
        library(plotly)
    
    
        #### prepare data ####
        adv <- read.csv("Advertising.csv")
    
        fit_tv <- lm(sales ~ TV, data = adv)  
    
        adv_plot <- data.frame(adv, fit = fit_tv$fitted.values)
    
        #### ggplot ####
        p1 <- ggplot(adv_plot, aes(x = TV, y = sales)) + 
                geom_segment(aes(x = TV, xend = TV, y = sales, yend = fit), size = 0.5, color = "lightgrey") + 
                geom_point(color = "red") + 
                geom_point(aes(y = fit), color = "blue") 
    
        p1
    
        #### Plotly ####
        p2 <- plot_ly(adv_plot, x = ~TV, y = ~sales, type = "scatter", mode = "markers", marker = list(color = "red", size = 5)) %>% 
                add_trace(x = ~TV, y = ~fit, type = "scatter", mode = "markers", marker = list(color = "blue", size = 5))
    
        line <- list(
                type = "line",
                line = list(color = "lightgrey"),
                xref = "x",
                yref = "y"
        )
    
        lines <- list()
        for (i in 1:length(adv_plot$sales)) {
                line[["x0"]] <- adv_plot$TV[i]
                line[["x1"]] <- adv_plot$TV[i]
                line[["y0"]] <- adv_plot$sales[i]
                line[["y1"]] <- adv_plot$fit[i]
                lines <- c(lines, list(line))
        }
        p2 <- layout(p2, shapes = lines, showlegend = FALSE)
        p2
    
    库(ggplot2)
    图书馆(绘本)
    ####准备数据####
    
    adv最后我自己设法找到了答案。分段和轨迹的顺序将误差线保留在背景中

    数据如下:

    代码如下:

        library(ggplot2)
        library(plotly)
        adv <- read.csv("Advertising.csv")
    
        fit_tv <- lm(sales ~ TV, data = adv)  
    
        adv_plot <- data.frame(adv, fit = fit_tv$fitted.values)
        p <- plot_ly(adv_plot, x = ~TV) %>%
                add_segments(x = ~TV, y = ~fit, xend = ~TV, yend = ~sales, mode = 'line', line = list(color = "lightgrey")) %>% 
                add_trace(y = ~sales, name = 'trace 0', type = "scatter", mode = 'markers', marker = list(color = "red", size = 5)) %>%
                add_trace(y = ~fit, name = 'trace 1', type = "scatter", mode = 'markers', marker = list(color = "blue", size = 5)) %>% 
                layout(showlegend = FALSE)
    
        p
    
    库(ggplot2)
    图书馆(绘本)
    adv%
    布局(showlegend=FALSE)
    P
    
    你试过了吗?
    plotly::ggplotly(p1)
    ?我在你的评论之后试过了。它很好用。它几乎与ggplot相同,添加了plotly交互功能。然而,我想完全用plotly来理解和学习如何使用和调整它。即使我不使用ggplotly的动机不是因为性能,但我今天早上在这篇文章中得到了回应:我设法找到了答案。如果你喜欢看,我已经把我问题的答案贴出来了。