2017-11-26 12 views
0

호기심에서 벗어나 플롯으로 ggplot 그래프를 재구성하려고합니다.플롯으로 ggplot 그래프 다시 그리기

간단한 선형 회귀의 예입니다. 그래프는 관찰 된 데이터, 회귀선 및 오류를 보여주는 수직선을 보여줍니다.

ggplot은 다음과 같다 : enter image description here

재구성 된 plotly 그래프는 다음과 같다 :

enter image description here

  1. 백에 에러를 표시하는 수직선을 푸시하는 방법이 포인트?
  2. 더 좋은 방법이 있습니까?

데이터는 여기에서 찾을 수 있습니다 : 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

당신이'plotly :: ggplotly (P1)을'봤어 : Advertising.csv

이 코드는? – Peter

+0

귀하의 의견을 따르려고했습니다. 그것은 잘 작동합니다. 플롯 상호 작용이 추가 된 ggplot과 거의 동일한 플롯입니다. 그러나 나는 그것을 사용하고 조정할 방법을 이해하고 배우는 것을 기만적으로 완전히하고 싶습니다. ggplotly를 사용하지 않기위한 동기가 성능 때문이 아니지만 오늘 아침에이 기사를 보았습니다 : [ggplotly vs plotly] (https://www.r-bloggers.com/comparing-plotly-ggplotly-plot-generation-times) /) –

+0

답변을 찾으러 관리합니다. 만약 당신이 골동품 그것을보고 내 질문에 대한 답변을 게시했습니다. –

답변

1

대답 나 자신을 발견 할 수 있었다. 세그먼트 및 추적의 순서는 백그라운드에서 오류 라인을 유지합니다.

데이터는 여기에 있습니다 :

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