Introduction

This tutorial will teach you how to build your first echarts4r graph! The package lends itself very well to this type of tutorial as we build plots by piping elements one after the other.

Run the snippet below to load the library and we’ll get started.

library(echarts4r)

In echarts4r, every single chart is initialised with the e_charts function, though it’s of very little use on its own: it produces a blank canvas. You can think of it as the function ggplot in the ggplot2 package. Also like the latter the first argument of that initialisation function is the data. Then again, somewhat reminiscent of ggplot2, we simply pipe (%>%) figures and options from then onwards.

Your first chart

Let’s plot your first chart with echarts4r., run the code below to see what it looks like!

e_charts(cars, speed) %>% 
  e_scatter(dist, symbol_size = 10)

Wehey, your first plot!

Let’s unravel what we just did. First we passed the dataset cars and specified the x axis speed in the initialisation function. We then piped the equivalent of a point geom in ggplot2 with e_scatter to which we specified the data that goes along the y axis (we also specified the symbol_size otherwise it’s a bit small).

This pretty much sums up how echarts4r works, let’s draw another chart.

Grouping

echarts4r understands (and exports) dplyr’s group_by function: we can use it like we’d use the group aesthetic in ggplot2.

iris %>%
  group_by(Species) %>%  
  e_charts(Sepal.Length) %>% 
  e_scatter(Sepal.Width, symbol_size = 10)

Make sure you ungroup your data if you do not want to plot it grouped!

Timeline

To build a timeline you don’t need much more than what we used so far, just add an argument: set timeline to TRUE in the initialisation function (e_charts).

iris %>%
  group_by(Species) %>%  
  e_charts(Sepal.Length) %>% 
  e_scatter(Sepal.Width, symbol_size = 10)

Hint: Set timeline to TRUE in e_charts.

iris %>%
  group_by(Species) %>%  
  e_charts(Sepal.Length, timeline = TRUE) %>% 
  e_scatter(Sepal.Width, symbol_size = 10)

Explore

If you want to add more “geoms,” simply pipe them along. Complete the code below so that it adds a e_line plot of the mpg from the mtcars dataset.

# add a line chart of `mpg`
mtcars %>% 
  e_charts(wt) %>% 
  e_scatter(qsec, symbol_size = 10)

Hint: You may want to use the e_line function.

mtcars %>% 
  e_charts(wt) %>% 
  e_scatter(qsec, symbol_size = 10) %>% 
  e_line(mpg)