Plotly4mtcars

Yuri K.

30 01 2017

Intro: plotly demo based on mtcars dataset

This is a sample illustration of the integration of interactive charts, created by plotly package and RMD compiled files. We shall use the mtcars data for this purpose. The basic plot of observed & fitted values of MPG estimates are as follows.

Simple nultivariate regression was used for assessment, having transmission type and horsepower as covariates.

The resulting figure is shown on the next slide.

MPG described by car horsepower and transmossion type

Appendix: used code

  require(plotly)
  mmtcars<-mtcars;mmtcars$am<-as.factor(mmtcars$am);levels(mmtcars$am)<-c("A","M")
  fit<-lm(mpg~hp+factor(am),data=mmtcars);  mmtcars$mpg_fitted<- fitted(fit)
  mmtcars$label<-paste(rownames(mmtcars),": mpg=",mmtcars$mpg,",\n hp=",mmtcars$hp," @",mmtcars$am,sep="")
  mmtcars %>%
    plot_ly(x = ~hp, 
            y = ~mpg, 
            color = ~am, 
            text=~label,
            type = "scatter", mode = "markers", name = "Data",
            marker = list(size = 10, opacity = 0.5), showlegend = F) %>% 
    add_trace(x = ~hp, 
              y = ~mpg_fitted, 
              color=~am, 
              type = "scatter", mode = "line", name = "Smooth",
              marker=list(size=0),
              line=list(width=3)
              ) %>%    
    layout(title = "Miles per gallon vs Horse Power", plot_bgcolor = "#e6e6e6")

Thank you!