Plot in R with echarts4r

Larn how to make everything from basic line graphs to racing bar charts — all interactive and easily animated — with the echarts4r R package.

Plot in R with echarts4r
Thinkstock

While I'thousand mostly settled on ggplot2 for static plots, I'grand always on the picket for ways to make interactive visualizations. echarts4r is one of my new favorite packages for this. Information technology'southward intuitive, powerful, and flexible.

The echarts4r package is an R wrapper for the echarts JavaScript library, an official Apache Software Foundation projection (information technology graduated from incubator condition in Dec). That helps me experience confident I can rely on the JavaScript lawmaking underlying the R bundle.

And so let's take a look at echarts4r.

Package author John Coene explains the basics in a getting started page:

  • Every function in the package starts with e_.
  • You start coding a visualization by creating an echarts object with the e_charts() part. That takes your data frame and x-axis column every bit arguments.
  • Next, y'all add a part for the blazon of chart (e_line(), e_bar(), etc.) with the y-axis series column name equally an statement.
  • The residuum is mostly customization!

Let's take a look.

Line charts with echarts4r

For example data, I downloaded and wrangled some housing cost info by U.s.a. city from Zillow. If you want to follow along, data instructions are at the cease of this commodity.

My houses_wide data frame has ane cavalcade for Month (I'chiliad simply looking at December for each year starting in 2007) and columns for each city.

Classes 'data.tabular array' and 'information.frame':	14 obs. of  10 variables:  $ Month        : Factor w/ fourteen levels "2007-12-31","2008-12-31",..: 1 2 three 4 v 6 7 8 9 x ...  $ Austin       : num  247428 240695 237653 232146 230383 ...  $ Boston       : num  400515 366284 352017 363261 353877 ...  $ Charlotte    : num  193581 185012 174552 162368 150636 ...  $ Chicago      : num  294717 254638 215646 193368 171936 ...  $ Dallas       : num  142281 129887 130739 122384 115999 ...  $ New York     : num  534711 494393 459175 461231 450736 ...  $ Phoenix      : num  239798 177223 141344 123984 114166 ...  $ San Francisco: num  920275 827897 763659 755145 709967 ...  $ Tampa        : num  248325 191450 153456 136778 120058 ...

I'll start by loading the echarts4r and dplyr packages. Note I'm using the development version of echarts4r to access the latest version of the echarts JavaScript library. You can install the dev version with these lines:

remotes::install_github"JohnCoene/echarts4r")
library(echarts4r)
library(dplyr)

In the code beneath, I create a basic echarts4r object with Calendar month as the x-axis column.

houses_wide %>%
e_charts(x = Calendar month)

If you're familiar with ggplot, this first step is similar: It creates an object, but there's no information in the visualization yet. Y'all'll see the ten axis but no y axis or data.

echarts4r x axis

Depending on your browser width, all the axis labels may not display because echarts4r is responsive by default — you don't accept to worry about the axis text labels overwriting each other if in that location'due south not enough room for them all.

Next, I'll add the blazon of nautical chart I want and the y-axis cavalcade. For a line nautical chart, that's the e_line() function. It needs at to the lowest degree one argument, the column with the values. The statement is calledserie, as in singular of series.

houses_wide %>%
e_charts(x = Calendar month) %>%
e_line(serie = `San Francisco`)
echarts line chart Screen shot past Sharon Machlis, IDG

Line chart of Zillow information created with echarts4r.

There are many other chart types available, including bar charts with e_bar(), area charts e_area(), scatter plots e_scatter(), box plots e_boxplot(), histograms e_histogram(), oestrus maps e_heatmap(), tree maps e_tree(), give-and-take clouds e_cloud(), and pie charts e_pie(). You can run across the total list on the echarts4r package website or in the help files.

Each of the chart-type functions take column names without quotation marks as arguments. That's similar to how ggplot works.

Just well-nigh functions listed hither have versions that have quoted column names. That lets you lot use variable names as arguments. John Coene calls those "escape-hatch" functions, and they have an underscore at the end of the office name, such as:

e_line(Boston)
my_city <- "Boston"
e_line_(my_city)

This makes information technology simple to create functions out of your chart code.

Side by side, I'll add a second city with another e_line() part.

houses_wide %>%
e_charts(x = Month) %>%
e_line(serie = `San Francisco`) %>%
e_line(serie = Boston)

In that location are no tooltips displayed past default, just I tin add those with the e_tooltips() function. Find that commas are added to the tooltip values by default, which is nice.

echarts4r line chart with two series and tooltips. Screen shot past Sharon Machlis, IDG

echarts4r line chart with two series and tooltips.

But the tooltip here could be even more useful if I could come across both values at the same time. I tin can do that with this office:

e_tooltip(trigger = "axis")

I can turn this line chart into a grouped bar chart just by swapping in e_bar() for e_line().

Customize chart colors with echarts4r

Y'all'll probably want to customize the colors for your charts at some point. There are thirteen born themes, which y'all tin meet on the echarts4r website. In the code below, I first save my chart in a variable called p and so I don't take to keep repeating that lawmaking. Then I add a theme, in this instance bee-inspired, with e_theme("bee-inspired")

p <- houses_wide %>%
e_charts(x = Month) %>%
e_line(serie = `San Francisco`) %>%
e_line(serie = Boston) %>%
e_tooltip(trigger = "axis")
p %>%
e_theme("bee-inspired")

You tin create your own theme from scratch or modify an existing one. There'south an online theme builder tool to help. To utilise that tool, create your customizations, download the JSON file for your theme, and use e_theme_custom("name_of_my_theme") to add information technology to a plot.

Yous tin also tweak a theme right in your graph lawmaking — for example, changing a theme's groundwork color with code such as:

p %>%
e_theme_custom("mytheme.json") %>%
e_color(background = "ivory")

You don't need to use a theme to customize your graph, however; the e_color() function works on graph defaults too. The outset argument fore_color() is a vector of colors for your lines, bars, points, whatever. Below I first create a vector of 3 colors (using color names or hex values). And so I add together that vector as the starting time argument to e_color():

my_colors <- c("darkblue", "#03925e", "purple")
p <- houses_wide %>%
e_charts(ten = Calendar month) %>%
e_line(serie = `San Francisco`) %>%
e_line(serie = Boston) %>%
e_line(serie = Austin) %>%
e_tooltip(trigger = "axis") %>%
e_color(my_colors)

RColorBrewer palettes

I don't meet RColorBrewer palettes built into echarts4r the mode they are in ggplot, only it'south easy to add them yourself. In the post-obit code group, I load the RColorBrewer library and create a vector of colors with the brewer.pal() part. I want three colors using the Dark2 palette (one of my favorites):

library(RColorBrewer)
my_colors <- brewer.pal(3, "Dark2")
my_colors
## [1] "#1B9E77" "#D95F02" "#7570B3"
p %>%
e_color(my_colors)
echarts4r line chart with an RColorBrewer palette Screen shot by Sharon Machlis, IDG

echarts4r line chart with an RColorBrewer palette.

Paletteer palettes

By the way, a similar format lets you use the R paletteer package to access a load of R palettes from many different R palette packages. The code below looks at the Color_Blind palette from the ggthemes collection and selects the beginning, second, and fifth of those colors.

library(paletteer)
paletteer_d("ggthemes::Color_Blind")
my_colors <- paletteer_d("ggthemes::Color_Blind")[c(i,ii,5)]
p %>%
e_color(my_colors)
color-blind palette from ggthemes Screen shot past Sharon Machlis, IDG

Color-bullheaded palette from ggthemes

If yous're not familiar with the paletteer package, the function paletteer_d() accesses whatsoever of the available discreet color palettes. Here I wanted Color_Blind from ggthemes, and I chose colors i, two, and five for the my_colors vector.

Long-format "tidy" data

If there are a lot of series in your data, you probably don't want to type out each i by proper noun in a separate role call. And you don't have to. echarts4r handles long-format "tidy" data elegantly.

For this group of examples, I'll use a data frame in long format with condo price info. Information on how to create your own copy of the data is at the cease of this commodity.

Don't miss the next code group: I utilise dplyr'south group_by() part on the data frame before running e_charts() on it, and echarts4r understands that. Now if I tell echarts4r to use Month for the x axis and Value for the y centrality, it knows to plot each group equally a separate series. (I'thousand also saving this graph to a variable chosen myplot.)

myplot <- condos %>%
group_by(City) %>% #<<
e_charts(x = Month) %>%
e_line(serie = Value) %>%
e_tooltip(trigger = "axis")
myplot
echarts4r line chart with legend at the top Screen shot by Sharon Machlis, IDG

echarts4r line chart with fable at the pinnacle.

The legend at the top of the graph isn't very helpful, though. If I want to find Tampa (the pink line), I can mouse over the legend, but information technology volition notwithstanding exist hard to see the highlighted pink line with so many other lines correct near it. Fortunately, there's a solution.

Custom legend

In the next lawmaking group, I add functions e_grid() and e_legend() to the graph.

myplot %>%
e_grid(right = '15%') %>%
e_legend(orient = 'vertical',
right = '5', superlative = '15%')

The e_grid(right = 'fifteen%') says I want my main graph visualization to accept 15% padding on the right side. The e_legend() role says to make the legend vertical instead of horizontal, add a v-pixel padding on the right, and add a 15% padding on the top.

Line chart with legend on the side Screen shot by Sharon Machlis, IDG

Line nautical chart with legend on the side.

That helps, just if I want to but meet Tampa, I need to click on every other legend item to turn it off. Some interactive information visualization tools let y'all double-click an detail to only prove that one. echarts handles this a little differently: Y'all tin add buttons to "invert" the selection process, so you simply see the items you click.

To do this, I added a selector argument to the e_legend() role. I saw those buttons in a sample echart JavaScript chart that used selector, only (as far as I know) it's not built-in functionality in echarts4r. John only hard-coded some of the functionality in the wrapper; but nosotros tin use all of it -- with the right syntax.

Translate JavaScript into echarts4r R code

A quick detour for a little "how this works under the hood" explanation. Beneath is an example John Coene has on the echarts4r site. You lot can see the original echarts JavaScript documentation in the image (you'll probably demand to click to expand it): tooltip.axisPointer.type. tooltip is an bachelor echarts4r function, e_tooltip(), so we can use that in R. axisPointer is a tooltip option, but it'south not part of the R package. Ane of axisPointer's options is type, which can accept a value of line, shadow, none, or cross.

accesspointer Apache Software Foundation

Then, we need to translate that JavaScript into R. We tin do that by using axisPointer as an statement of e_tooltip(). Here's the important part: For the value of axisPointer, we create a listing, with the list containingblazon = "cross".

e_tooltip(axisPointer = list(type = "cross"))

If you lot know how this works, y'all have all the power and flexibility of the unabridged echarts JavaScript library, not simply the functions and arguments John Coene coded into the bundle.

To create two selector buttons, this is the JavaScript syntax from the echarts site:

selector: [
{
blazon: 'inverse',
championship: 'Invert'
},
{
type: 'all or inverse',
title: 'Changed'
}
]

And this is the R syntax:

e_legend(              
selector = list(
list(blazon = 'inverse', title = 'Invert'),
list(type = 'all', title = 'Reset')
)
)

Each fundamental-value pair gets its ain list within the selector list. Everything'due south a list, sometimes nested. That's it!

Plot titles in echarts4r

OK let'south plough to something easier: a title for our graph. echarts4r has an e_title() role that can take arguments text for the title text, subtext for the subtitle text, and also link and sublink if yous want to add a clickable URL to either the title or subtitle.

If I want to change the alignment of the headline and subheadline, the argument is left. left can take a number for how much padding y'all want betwixt the left border and the commencement of text, or it can take center or right for alignment as you see here:

myplot %>%              
e_title(text = "Monthly Median Unmarried-Family Home Prices",
subtext = "Source: Zillow.com",
sublink = "https://world wide web.zillow.com/research/information/",
left = "middle"
)

left = "center" isn't very intuitive for new users, only it does make some sense if y'all know the background.

Colour charts by category with echarts4r

For these color-by-group demos, I'll utilise a data set with columns for the city, month, condo value, single-family home value, and "region" (which I but made up for purposes of coloring by grouping; information technology's non a Zillow region).

head(all_data_w_type_columns, two)     City      Month  Condo SingleFamily Region one Austin 2007-12-31 221734       247428  Due south 2 Austin 2008-12-31 210860       240695  S

Below is code for a scatter plot to come across if unmarried-family and condo prices move in tandem. Because I used dplyr'south group_by() on the data before creating a besprinkle plot, the plot is colored by region. I was too able to ready the dot size with symbol_size.

This code cake adds something else to the plot: a few "toolbox features" at the pinnacle correct of the graph. I included zoom, reset, view the underlying information, and salvage the plot every bit an image, but at that place are several others.

all_data_w_type_columns %>%              
group_by(Region) %>%
e_charts(SingleFamily) %>%
e_scatter(Condo, symbol_size = half-dozen) %>%
e_legend(Fake) %>%
e_tooltip() %>%
e_toolbox_feature("dataZoom") %>%
e_toolbox_feature(feature = "reset") %>%
e_toolbox_feature("dataView") %>%
e_toolbox_feature("saveAsImage")
Scatter plot with echarts4r Screen shot by Sharon Machlis, IDG

At that place are several statistical functions available, including regression lines and error bars, such as e_lm(Condo ~ SingleFamily, color = "green") to add together a linear regression line.

Animations with echarts4r

I'll wrap up our echarts4r tour with some easy animations.

For these demos, I'll employ data from the U.s. CDC on vaccinations by state: doses administered compared to vaccine doses received, to see which states are doing the best job of getting vaccines they have into people's arms quickly. The column I desire to graph is PctUsed. I also added a color cavalcade if I want to highlight 1 state with a unlike color, in this case Massachusetts.

Yous can download the data from GitHub:

mydata <- readr::read_csv("https://gist.githubusercontent.com/smach/194d26539b0d0deb9f6ac5ca2e7d49d0/raw/f0d3362e06e3cb7dbfc0c9df67e259f1e9dfb898/timeline_data.csv")
str(mydata) spec_tbl_df [112 × vii] (S3: spec_tbl_df/tbl_df/tbl/data.frame)  $ Country            : chr [1:112] "CT" "MA" "ME" "NH" ...  $ TotalDistributed : num [one:112] 740300 1247600 254550 257700 3378300 ...  $ TotalAdministered: num [1:112] 542414 806376 178449 166603 2418074 ...  $ ReportDate       : Appointment[1:112], format: "2021-02-08" "2021-02-08" "2021-02-08" "2021-02-08" ...  $ Used             : num [1:112] 0.733 0.646 0.701 0.646 0.716 ...  $ PctUsed          : num [one:112] 73.3 64.half-dozen lxx.1 64.6 71.half dozen 62.7 77.8 72.i 62.v 70.i ...  $ colour            : chr [1:112] "#3366CC" "#003399" "#3366CC" "#3366CC"            

Below is lawmaking for an animated timeline. If I grouping my data past date, add together timeline = TRUE to e_charts() and autoPlay = TRUE to the timeline options function, I create an autoplaying timeline.timeline = True is a very easy way to animate data by time in a bar graph.

In the remainder of this next code grouping, I prepare the bars to exist all one color using theitemStyle argument. The rest of the code is more styling: Turn the legend off, add labels for the bars with e_labels(), add together a title with a font size of 24, and leave a 100-pixel space between the top of the graph grid and the top of the entire visualization.

mydata %>%              
group_by(ReportDate) %>% #<<
e_charts(State, timeline = True) %>% #<<
e_timeline_opts(autoPlay = TRUE, top = xl) %>% #<<
e_bar(PctUsed, itemStyle = list(colour = "#0072B2")) %>%
e_legend(show = Imitation) %>%
e_labels(position = 'insideTop') %>%
e_title("Per centum Received Covid-xix Vaccine Doses Administered",
left = "heart", top = 5,
textStyle = list(fontSize = 24)) %>%
e_grid(superlative = 100)

Run the code on your own system if you lot want to see an animated version of this static chart:

echarts4r timeline Screen shot by Sharon Machlis, IDG

Static image of an animated echarts4r timeline.

Animating a line chart is equally easy as adding the e_animation() office. Charts are animated past default, but you can brand the duration longer to create a more than noticeable effect, such equally e_animation(duration = 8000):

mydata %>%
group_by(Land) %>%
e_charts(ReportDate) %>%
e_line(PctUsed) %>%
e_animation(elapsing = 8000)

I suggest y'all try running this code locally, too, to encounter the animation effect.

Racing bars

Racing confined are available in echarts version 5. At the time this article was published, you needed the GitHub version of echarts4r (the R bundle) to utilize echarts version 5 features (from the JavaScript library). You can see what racing confined look like in my video beneath:

This is the full code:

mydata %>%
group_by(ReportDate) %>%
e_charts(Land, timeline = TRUE) %>%
e_bar(PctUsed, realtimeSort = True, itemStyle = list(
borderColor = "black", borderWidth = '1')
) %>%
e_legend(show = FALSE) %>%
e_flip_coords() %>%
e_y_axis(inverse = True) %>%
e_labels(position = "insideRight",
formatter = htmlwidgets::JS("
role(params){
return(params.value[0] + '%')
}
") ) %>%
e_add("itemStyle", color) %>%
e_timeline_opts(autoPlay = True, top = "55") %>%
e_grid(top = 100) %>%
e_title(paste0("Per centum Vaccine Dose Administered "),
subtext = "Source: Analysis of CDC Data",
sublink = "https://covid.cdc.gov/covid-data-tracker/#vaccinations",
left = "eye", top = 10)

Racing confined lawmaking explainer

The code starts with the data frame, then uses dplyr's group_by() to group the information by date — you lot accept to group by date for timelines and racing bars.

Adjacent, I create an e_charts object with State as the 10 axis, and I include timeline = True, and add together e_bar(PctUsed) to make a bar nautical chart using the PctUsed column for y values. One new matter we haven't covered yet is realtimeSort = Truthful.

The other lawmaking inside e_bar() creates a blackness border line around the bars (non necessary, but I know some people would like to know how to do that). I besides turn off the legend, since it's not helpful here.

The side by side line, e_flip_coords(), changes the graph from vertical to horizontal bars. e_y_axis(inverse = True) sorts the confined from highest to everyman.

The e_labels() function adds a value label to the bars at the inside correct position. All the formatter code uses JavaScript to make a custom format for how the labels appear — in this case I'm adding a pct sign. That'due south optional.

Label and tooltip formatting

The format syntax is useful to know, because yous tin use the same syntax to customize tooltips. params.value[0] is the x-centrality value and params.value[1] is the y-axis value. Yous concatenate values and strings together in JavaScript with the plus sign. For example:

              formatter = htmlwidgets::JS("
function(params){
return('Ten equals ' + params.value[0] + 'Y equals' + params.value[1])
}

There's more information nigh formatting tooltips on the echarts4r site.

The e_add("itemStyle", colour) office is where I map the colors in my data'south colour column to the confined, using itemStyle. This is quite dissimilar from ggplot syntax and may take a piffling getting used to if you're a tidyverse user.

Finally, I added a championship and subtitle, a clickable URL for the subtitle, and some padding effectually the graph grid and the headline then they didn't see each other. Run this code, and you should take racing bars.

More resource

For more than on echarts4r, check out the package website at https://echarts4r.john-coene.com and the echarts JavaScript library site at https://echarts.apache.org. And for more R tips and tutorials, head to my Do More than With R page!