Last updated: 2018-03-29

Code version: f93372a

I came across one website introducing plotly R package, and was addicted for a few days, just share some of these amazing plots with you. The main scheme is introduce three basic examples, followed by scatter plot, line plot and ribbons.I will conclude this section with two great animation examples.

##install.packages("plotly")
##packageVersion("plotly")
library(plotly)
library(ggplot2)

Basic example 1

Interface modified by layout() function:“click + drag”event, rangeslider() will add a slider under this figure.

library(forecast)
p <- ggplot(fortify(gold), aes(x, y)) + geom_line()
gg <- ggplotly(p)
layout(gg, dragmode = "pan")
##rangeslider(gg)

Basic example 2

Look at and learn the basic structre , firstly use ggplotly(), then %>% link several matrics.

p <- ggplot(MASS::geyser, aes(x = waiting, y = duration)) +
  geom_density2d()
ggplotly(p, originalData = FALSE) %>% 
  group_by(piece) %>%
  slice(which.min(y)) %>% 
  add_text(
    text = ~level, size = I(10), color = I("black"), hoverinfo = "none"
  )

Basic example 3

p <- ggplot(mtcars, aes(x = wt, y = mpg)) +
  geom_point() + geom_smooth()
style(p, hoverinfo = "none", traces = 2:3)

Of course, we even could add annotations in detailed positions by function add_annotations() and add_segments().

p <- ggplot(mtcars, aes(x = wt, y = mpg)) +
  geom_point() + geom_smooth()
p %>%
  ggplotly(layerData = 2, originalData = FALSE) %>%
  add_fun(function(p) {
    p %>% slice(which.max(se)) %>%
      add_segments(x = ~x, xend = ~x, y = ~ymin, yend = ~ymax) %>%
      add_annotations("Maximum uncertainty", ax = 60)
  }) %>%
  add_fun(function(p) {
    p %>% slice(which.min(se)) %>%
      add_segments(x = ~x, xend = ~x, y = ~ymin, yend = ~ymax) %>%
      add_annotations("Minimum uncertainty")
  })

## 2D and 3D Scatter plot This time we use plot_ly(), previous sections are all employed ggplotly().

##I(2)is triangle, I(3)is +
subplot(
  plot_ly(x = 1:25, y = 1:25, symbol = I(1:25), name = "pch"),
  plot_ly(mpg, x = ~cty, y = ~hwy) %>% 
    add_markers(symbol = I(1), color = I("red"),name = "red")
)
p <- plot_ly(mpg, x = ~cty, y = ~hwy, alpha = 0.5)
subplot(
  add_markers(p, color = ~cyl, showlegend = F,name = "mpg") %>% 
    colorbar(title = "Viridis")
)

Last ones are two 3D examples, you are free to rotate the figures.

plot_ly(mpg, x = ~cty, y = ~hwy, z = ~cyl) %>%
  add_markers(color = ~cyl)
x <- seq_len(nrow(volcano)) + 100
y <- seq_len(ncol(volcano)) + 500
plot_ly() %>% add_surface(x = ~x, y = ~y, z = ~volcano)

A powerful functiom to visualize data iris:

pm <- GGally::ggpairs(iris)
ggplotly(pm)

Line plots

Lower image are the same data with upper image, just to compare the effects of add_lines(p, color = ~city) and add_lines(p, linetype = ~city).

library(dplyr)
top5 <- txhousing %>%
  group_by(city) %>%
  summarise(m = mean(sales, na.rm = TRUE)) %>%
  arrange(desc(m)) %>%
  top_n(5)

p <- semi_join(txhousing, top5, by = "city") %>%
  plot_ly(x = ~date, y = ~median)
subplot(
  add_lines(p, color = ~city),
  add_lines(p, linetype = ~city),
  shareX = TRUE, nrows = 2
)

Ribbons

library(broom)
m <- lm(mpg ~ wt, data = mtcars)
broom::augment(m) %>%
  plot_ly(x = ~wt, showlegend = FALSE) %>%
  add_markers(y = ~mpg, color = I("red")) %>%
  add_ribbons(ymin = ~.fitted - 1.96 * .se.fit, 
              ymax = ~.fitted + 1.96 * .se.fit, color = I("gray80")) %>%
  add_lines(y = ~.fitted, color = I("steelblue"))

Animation 1

Return to use function ggplotly()

data(gapminder, package = "gapminder")
head(gapminder)
# A tibble: 6 x 6
  country     continent  year lifeExp      pop gdpPercap
  <fct>       <fct>     <int>   <dbl>    <int>     <dbl>
1 Afghanistan Asia       1952    28.8  8425333      779.
2 Afghanistan Asia       1957    30.3  9240934      821.
3 Afghanistan Asia       1962    32.0 10267083      853.
4 Afghanistan Asia       1967    34.0 11537966      836.
5 Afghanistan Asia       1972    36.1 13079460      740.
6 Afghanistan Asia       1977    38.4 14880372      786.
gg <- ggplot(gapminder, aes(gdpPercap, lifeExp, color = continent)) +
  geom_point(aes(size = pop, frame = year, ids = country)) +
  scale_x_log10()
ggplotly(gg)

Animation 2

meanLife <- with(gapminder, tapply(lifeExp, INDEX = continent, mean))
gapminder$continent <- factor(
  gapminder$continent, levels = names(sort(meanLife))
)
base <- gapminder %>%
  plot_ly(x = ~gdpPercap, y = ~lifeExp, size = ~pop, 
          text = ~country, hoverinfo = "text") %>%
  layout(xaxis = list(type = "log"))
base %>%
  add_markers(data = gapminder, frame = ~continent) %>%
  hide_legend() %>%
  animation_opts(frame = 1000, transition = 0, redraw = FALSE)

Session information

sessionInfo()
R version 3.4.2 (2017-09-28)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS Sierra 10.12.1

Matrix products: default
BLAS: /Library/Frameworks/R.framework/Versions/3.4/Resources/lib/libRblas.0.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/3.4/Resources/lib/libRlapack.dylib

locale:
[1] zh_CN.UTF-8/zh_CN.UTF-8/zh_CN.UTF-8/C/zh_CN.UTF-8/zh_CN.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] broom_0.4.3   dplyr_0.7.4   bindrcpp_0.2  forecast_8.2  plotly_4.7.1 
[6] ggplot2_2.2.1

loaded via a namespace (and not attached):
 [1] Rcpp_0.12.16        lattice_0.20-35     tidyr_0.7.2        
 [4] zoo_1.8-1           utf8_1.1.3          assertthat_0.2.0   
 [7] rprojroot_1.3-2     digest_0.6.15       lmtest_0.9-35      
[10] psych_1.7.8         mime_0.5            R6_2.2.2           
[13] plyr_1.8.4          backports_1.1.2     evaluate_0.10.1    
[16] httr_1.3.1          pillar_1.2.1        rlang_0.2.0        
[19] lazyeval_0.2.1      curl_3.1            rstudioapi_0.7     
[22] data.table_1.10.4-3 fracdiff_1.4-2      TTR_0.23-3         
[25] rmarkdown_1.8       labeling_0.3        stringr_1.2.0      
[28] foreign_0.8-69      htmlwidgets_0.9     munsell_0.4.3      
[31] shiny_1.0.5         compiler_3.4.2      httpuv_1.3.5       
[34] pkgconfig_2.0.1     mnormt_1.5-5        htmltools_0.3.6    
[37] nnet_7.3-12         tibble_1.4.2        quadprog_1.5-5     
[40] reshape_0.8.7       viridisLite_0.3.0   crayon_1.3.4       
[43] MASS_7.3-48         grid_3.4.2          nlme_3.1-131       
[46] jsonlite_1.5        xtable_1.8-2        GGally_1.3.2       
[49] gtable_0.2.0        git2r_0.21.0        magrittr_1.5       
[52] scales_0.5.0.9000   quantmod_0.4-12     cli_1.0.0          
[55] stringi_1.1.6       reshape2_1.4.3      tseries_0.10-43    
[58] timeDate_3043.102   xts_0.10-2          RColorBrewer_1.1-2 
[61] tools_3.4.2         glue_1.2.0          purrr_0.2.4        
[64] crosstalk_1.0.0     parallel_3.4.2      yaml_2.1.16        
[67] colorspace_1.3-2    knitr_1.18          bindr_0.1          

This R Markdown site was created with workflowr