Valter Beaković
Valter Beaković

Reputation: 3250

Redrawing a ggplot graph with plotly

Out of curiosity I am trying to reconstruct a ggplot graph with plotly.

It is an example of a simple linear regression. The graph shows the observed data, the regression line and vertical lines showing the errors.

The ggplot looks like this: enter image description here

The reconstructed plotly graph looks like this:

enter image description here

  1. Is there a way to push the vertical lines showing the errors to the back of the points?
  2. Is there a better approach?

The data may be found here: Advertising.csv

This is the code used to make the plots:

    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

Upvotes: 0

Views: 411

Answers (1)

Valter Beaković
Valter Beaković

Reputation: 3250

At the end managed to find the answer myself. The order of the segments and traces keep the error lines in the background.

The data is here: Advertising.csv

This is the code:

    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

Upvotes: 1

Related Questions