用plotly重绘gg​​plot图

时间:2017-11-26 19:49:49

标签: r ggplot2 plotly

出于好奇,我试图用剧情重建ggplot图。

这是简单线性回归的一个例子。该图显示了观察到的数据,回归线和显示错误的垂直线。

ggplot看起来像这样: enter image description here

重建的情节图如下所示:

enter image description here

  1. 有没有办法将显示错误的垂直线推到点的后面?
  2. 有更好的方法吗?
  3. 可在此处找到数据: Advertising.csv

    这是用于制作图表的代码:

        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
    

1 个答案:

答案 0 :(得分:1)

最后设法找到答案。段和跟踪的顺序将错误行保留在后台。

数据在此处:Advertising.csv

这是代码:

    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