• Stars
    star
    513
  • Rank 82,788 (Top 2 %)
  • Language
    R
  • License
    Other
  • Created about 6 years ago
  • Updated 4 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

R Interface to D3 Visualizations

r2d3: R Interface to D3 Visualizations

R-CMD-check CRAN status Codecov test coverage

The r2d3 package provides a suite of tools for using D3 visualizations with R, including:

  • Translating R objects into D3 friendly data structures

  • Rendering D3 scripts within the RStudio Viewer and R Notebooks

  • Publishing D3 visualizations to the web

  • Incorporating D3 scripts into R Markdown reports, presentations, and dashboards

  • Creating interactive D3 applications with Shiny

  • Distributing D3 based htmlwidgets in R packages


With r2d3, you can bind data from R to D3 visualizations like the ones found on https://github.com/d3/d3/wiki/Gallery, https://bl.ocks.org/, and https://vida.io/explore:

D3 visualizations created with r2d3 work just like R plots within RStudio, R Markdown documents, and Shiny applications.

Getting Started

First, install the package from GitHub as follows:

devtools::install_github("rstudio/r2d3")

Next, install the preview release of RStudio v1.2 of RStudio (you need this version of RStudio to take advantage of various integrated tools for authoring D3 scripts with r2d3).

Once you’ve installed the package and the RStudio v1.2 preview release you have the tools required to work with r2d3. Below, we’ll describe basic workflow within RStudio and techniques for including visualizations in R Markdown and Shiny applications.

About D3

Creating data visualizations with r2d3 requires lots of custom SVG graphics programming (similar to creating custom grid graphics in R). It’s therefore a good fit when you need highly custom visualizations that aren’t covered by existing libraries. If on the other hand you are looking for pre-fabricated D3 / JavaScript visualizations, check out the packages created using htmlwidgets, which provide a much higher level interface.

If you are completely new to D3, you may also want to check out the article on Learning D3 before proceeding further.

D3 Scripts

To use r2d3, write a D3 script and then pass R data to it using the r2d3() function. For example, here’s a simple D3 script that draws a bar chart (“barchart.js”):

// !preview r2d3 data=c(0.3, 0.6, 0.8, 0.95, 0.40, 0.20)

var barHeight = Math.floor(height / data.length);

svg
  .selectAll("rect")
  .data(data)
  .enter()
  .append("rect")
  .attr("width", function (d) {
    return d * width;
  })
  .attr("height", barHeight)
  .attr("y", function (d, i) {
    return i * barHeight;
  })
  .attr("fill", "steelblue");

To render the script within R you call the r2d3() function:

library(r2d3)
r2d3(data=c(0.3, 0.6, 0.8, 0.95, 0.40, 0.20), script = "barchart.js")

Which results in the following visualization:

D3 Variables

Note that data is provided to the script using the data argument to the r2d3() function. This data is then automatically made available to the D3 script. There are a number of other special variables available within D3 scripts, including:

  • data - The R data converted to JavaScript.
  • svg - The svg container for the visualization
  • width - The current width of the container
  • height - The current height of the container
  • options - Additional options provided by the user
  • theme - Colors for the current theme

When you are learning D3 or translating D3 examples for use with R it’s important to keep in mind that D3 examples will generally include code to load data, create an SVG or other root element, and establish a width and height for the visualization.

On the other hand with r2d3, these variables are provided automatically so do not need to be created. The reasons these variables are provided automatically are:

  1. So that you can dynamically bind data from R to visualizations; and

  2. So that r2d3 can automatically handle dynamic resizing for your visualization. Most D3 examples have a static size. This if fine for an example but not very robust for including the visualization within a report, dashboard, or application.

D3 Preview

The RStudio v1.2 preview release of RStudio includes support for previewing D3 scripts as you write them. To try this out, create a D3 script using the new file menu:

A simple template for a D3 script (the barchart.js example shown above) is provided by default. You can use the Preview command (Ctrl+Shift+Enter) to render the visualization:

You might wonder where the data comes from for the preview. Note that there is a special comment at the top of the D3 script:

// !preview r2d3 data=c(0.3, 0.6, 0.8, 0.95, 0.40, 0.20)

This comment enables you to specify the data (along with any other arguments to the r2d3() function) to use for the preview.

R Markdown

You can include D3 visualizations in an R Markdown document or R Notebook. You can do this by calling the r2d3() function from within an R code chunk:

---
output: html_document
---

```{r}
library(r2d3)
r2d3(data=c(0.3, 0.6, 0.8, 0.95, 0.40, 0.20), script = "barchart.js")
```

You can also include D3 visualization code inline using the d3 R Markdown engine:

```{r setup}
library(r2d3)
bars <- c(10, 20, 30)
```
```{d3 data=bars, options=list(color = 'orange')}
svg.selectAll('rect')
  .data(data)
  .enter()
    .append('rect')
      .attr('width', function(d) { return d * 10; })
      .attr('height', '20px')
      .attr('y', function(d, i) { return i * 22; })
      .attr('fill', options.color);
```

Note that in order to use the d3 engine you need to add library(r2d3) to the setup chunk (as illustrated above).

Shiny

The renderD3() and d3Output() functions enable you to include D3 visualizations within Shiny applications:

library(shiny)
library(r2d3)

ui <- fluidPage(
  inputPanel(
    sliderInput("bar_max", label = "Max:",
                min = 0.1, max = 1.0, value = 0.2, step = 0.1)
  ),
  d3Output("d3")
)

server <- function(input, output) {
  output$d3 <- renderD3({
    r2d3(
      runif(5, 0, input$bar_max),
      script = system.file("examples/baranims.js", package = "r2d3")
    )
  })
}

shinyApp(ui = ui, server = server)

See the article on Using r2d3 with Shiny to learn more (including how to create custom Shiny inputs that respond to user interaction with D3 visualizations).

Learning More

To learn the basics of D3 and see some examples that might inspire your own work, check out:

  • Learning D3 - Suggested resources for learning how to create D3 visualizations.

  • Gallery of Examples - Learn from a wide variety of example D3 visualizations.

For next steps on learning on how to use r2d3, see these articles:

Once you are familar with the basics, check out these articles on more advanced topics:

Using r2d3 with Shiny - Deriving insights from data is streamlined when users are able to modify a Shiny input, or click on a D3 visualization, and that action produces new results.

  • CSS and JavaScript Dependencies

    • Incorporating external CSS styles and JavaScript libraries into your visualizations.
  • Advanced Rendering with Callbacks

    • An alternate way to organize D3 scripts that enables you to distinguish between initialization and re-rendering based on new data, as well as handle resizing more dynamically.
  • Package Development – Create re-usable D3 visualizations by including them in an R package.

More Repositories

1

cheatsheets

Posit Cheat Sheets - Can also be found at https://posit.co/resources/cheatsheets/.
TeX
5,540
star
2

shiny

Easy interactive web applications with R
R
5,209
star
3

rstudio

RStudio is an integrated development environment (IDE) for R
Java
4,432
star
4

bookdown

Authoring Books and Technical Documents with R Markdown
JavaScript
3,613
star
5

rmarkdown

Dynamic Documents for R
R
2,737
star
6

shiny-examples

JavaScript
1,927
star
7

gt

Easily generate information-rich, publication-quality tables from R
R
1,892
star
8

blogdown

Create Blogs and Websites with R Markdown
R
1,694
star
9

reticulate

R Interface to Python
R
1,604
star
10

webinars

Code and slides for RStudio webinars
HTML
1,510
star
11

rticles

LaTeX Journal Article Templates for R Markdown
TeX
1,402
star
12

plumber

Turn your R code into a web API.
R
1,355
star
13

tensorflow

TensorFlow for R
R
1,313
star
14

renv

renv: Project environments for R.
R
953
star
15

pagedown

Paginate the HTML Output of R Markdown with CSS for Print
R
861
star
16

shinydashboard

Shiny Dashboarding framework
CSS
852
star
17

pointblank

Data quality assessment and metadata reporting for data frames and database tables
R
824
star
18

keras

R Interface to Keras
R
818
star
19

flexdashboard

Easy interactive dashboards for R
JavaScript
788
star
20

leaflet

R Interface to Leaflet Maps
JavaScript
784
star
21

rmarkdown-book

R Markdown: The Definitive Guide (published by Chapman & Hall/CRC in July 2018)
RMarkdown
738
star
22

ggvis

Interactive grammar of graphics for R
R
709
star
23

shiny-server

Host Shiny applications over the web.
JavaScript
700
star
24

rstudio-conf

Materials for rstudio::conf
HTML
696
star
25

learnr

Interactive Tutorials with R Markdown
R
695
star
26

RStartHere

A guide to some of the most useful R Packages that we know about
R
656
star
27

py-shiny

Shiny for Python
Python
627
star
28

DT

R Interface to the jQuery Plug-in DataTables
JavaScript
581
star
29

rmarkdown-cookbook

R Markdown Cookbook. A range of tips and tricks to make better use of R Markdown.
RMarkdown
562
star
30

blastula

Easily send great-looking HTML email messages from R
R
522
star
31

bookdown-demo

A minimal book example using bookdown
CSS
476
star
32

hex-stickers

RStudio hex stickers
R
434
star
33

distill

Distill for R Markdown
HTML
416
star
34

bslib

Tools for theming Shiny and R Markdown via Bootstrap 3, 4, or 5.
SCSS
414
star
35

packrat

Packrat is a dependency management system for R
R
394
star
36

tufte

Tufte Styles for R Markdown Documents
R
385
star
37

dygraphs

R interface to dygraphs
JavaScript
361
star
38

revealjs

R Markdown Format for reveal.js Presentations
JavaScript
316
star
39

pins-r

Pin, Discover and Share Resources
R
299
star
40

fontawesome

Easily insert FontAwesome icons into R Markdown docs and Shiny apps
R
287
star
41

profvis

Visualize R profiling data
JavaScript
285
star
42

crosstalk

Inter-htmlwidget communication for R (with and without Shiny)
JavaScript
284
star
43

config

config package for R
R
247
star
44

pool

Object Pooling in R
R
242
star
45

thematic

Theme ggplot2, lattice, and base graphics based on a few simple settings.
R
237
star
46

Intro

Course materials for "Introduction to Data Science with R", a video course by RStudio and O'Reilly Media
R
234
star
47

tinytex-releases

Windows/macOS/Linux binaries and installation methods of TinyTeX
PowerShell
226
star
48

shinytest

Automated testing for shiny apps
JavaScript
222
star
49

httpuv

HTTP and WebSocket server package for R
C
217
star
50

nomnoml

Sassy 'UML' Diagrams for R
JavaScript
216
star
51

shinymeta

Record and expose Shiny app logic using metaprogramming
R
212
star
52

htmltools

Tools for HTML generation and output
R
201
star
53

shinyuieditor

A GUI for laying out a Shiny application that generates clean and human-readable UI code
JavaScript
200
star
54

promises

A promise library for R
R
193
star
55

vetiver-r

Version, share, deploy, and monitor models
R
175
star
56

rstudioapi

Safely access RStudio's API (when available)
R
161
star
57

gradethis

Tools for teachers to use with learnr
R
159
star
58

concept-maps

Concept maps for all things data science
HTML
158
star
59

master-the-tidyverse

Course contents for Master the Tidyverse
156
star
60

shinythemes

Themes for Shiny
R
152
star
61

ShinyDeveloperConference

Materials collected from the First Shiny Developer Conference Palo Alto, CA January 30-31 2016
HTML
152
star
62

chromote

Chrome Remote Interface for R
R
145
star
63

shiny-gallery

Code and other documentation for apps in the Shiny Gallery ✨
HTML
140
star
64

sortable

R htmlwidget for Sortable.js
R
124
star
65

rsconnect

Publish Shiny Applications, RMarkdown Documents, Jupyter Notebooks, Plumber APIs, and more
R
120
star
66

reactlog

Shiny Reactivity Visualizer
JavaScript
119
star
67

redx

dynamic nginx configuration
Lua
118
star
68

bigdataclass

Two-day workshop that covers how to use R to interact databases and Spark
R
114
star
69

r-system-requirements

System requirements for R packages
Shell
111
star
70

shinyapps

Deploy Shiny applications to ShinyApps
110
star
71

webshot2

Take screenshots of web pages from R
R
109
star
72

shinyloadtest

Tools for load testing Shiny applications
HTML
108
star
73

shinyvalidate

Input validation package for the Shiny web framework
JavaScript
108
star
74

r-docker

Docker images for R
Dockerfile
105
star
75

miniUI

R
102
star
76

sass

Sass compiler package for R
C++
102
star
77

shinytest2

R
98
star
78

keras-customer-churn

Customer Churn Shiny Application
R
98
star
79

r-builds

an opinionated environment for compiling R
Shell
91
star
80

r-manuals

A re-styled version of the R manuals
R
85
star
81

addinexamples

An R package showcasing how RStudio addins can be registered and used.
R
85
star
82

shinyapps-package-dependencies

Collection of bash scripts that install R package system dependencies
R
74
star
83

markdown

The first generation of Markdown rendering for R (born in 2012). Originally based on the C library sundown. Now based on commonmark. Note that this package is markdown, not *rmarkdown*.
R
72
star
84

R-Websockets

HTML 5 Websockets implementation for R
R
68
star
85

webdriver

WebDriver client in R
R
68
star
86

beyond-dashboard-fatigue

Materials for the RStudio webinar 'Beyond Dashboard Fatigue'
R
66
star
87

cloudml

R interface to Google Cloud Machine Learning Engine
R
65
star
88

shinylive

Run Shiny on Python (compiled to wasm) in the browser
TypeScript
61
star
89

rstudio-conf-2022-program

rstudio::conf(2022, "program")
R
61
star
90

rstudio-docker-products

Docker images for RStudio Professional Products
Just
59
star
91

bookdown.org

Source documents to generate the bookdown.org website
R
59
star
92

education.rstudio.com

CSS
57
star
93

tfestimators

R interface to TensorFlow Estimators
R
57
star
94

vetiver-python

Version, share, deploy, and monitor models.
Python
55
star
95

tfprobability

R interface to TensorFlow Probability
R
54
star
96

sparkDemos

HTML
53
star
97

shiny-incubator

Examples and ideas that don't belong in the core Shiny package and aren't officially supported.
JavaScript
53
star
98

connections

https://rstudio.github.io/connections/
R
52
star
99

swagger

Swagger is a collection of HTML, Javascript, and CSS assets that dynamically generate beautiful documentation from a Swagger-compliant API.
HTML
51
star
100

leaflet.mapboxgl

Extends the R Leaflet package with a Mapbox GL JS plugin to allow easy drawing of vector tile layers.
R
49
star