Easily create interactive ggplot graphs in R with ggiraph

Static visualizations are usually more than enough to explain to stories with your facts. But occasionally you want to add interactivity, so users can hover more than graphs to see underlying facts or backlink their hover more than 1 visualization to highlighting facts in yet another. 

R has a number of offers for building interactive graphics like echarts4r, plotly, and highcharter. I like and use all of those. But for straightforward linking of interactive graphs, it’s hard to defeat ggiraph.

From ggplot to ggiraph in 3 straightforward steps

There are 3 straightforward steps to transform ggplot code into an interactive graph:

  1. Use a ggiraph interactive geom in its place of a “regular” ggplot geom. The format is straightforward to recall: Just add _interactive to your common geom. So, geom_col() for a frequent bar chart would be geom_col_interactive(), geom_place() would be geom_place_interactive(), and so on. 
  2. Include at the very least 1 interactive argument to the graph’s aes() mapping: tooltip, facts_id, or onclick. That facts_id argument is what connects two graphics, permitting you hover more than 1 and have an effect on the exhibit of yet another 1 — all without having Shiny. 
  3. Following building your ggiraph dataviz object, use the girafe() function to transform it into a JavaScript graphic. Of course, which is girafe() like the animal but with 1 f. (That is how you spell it in French, and the creator of ggiraph, David Gohel, lives in Paris.)

Put in the R offers

If you’d like to adhere to along with the code in this tutorial, you are going to need to have the ggplot2, ggiraph, dplyr, and patchwork offers from CRAN on your program as effectively as ggiraph. And, to generate a map, I’ll be using Bob Rudis’s albersusa offer, which isn’t on CRAN. You can set up it from GitHub with 

fobs::set up_github("hrbrmstr/albersusa")


devtools::set up_github("hrbrmstr/albersusa")

Prepare the facts

For facts, I’m heading to use the latest US Covid vaccination facts by state accessible from the Our Entire world in Knowledge GitHub repository.

In the code below, I’m loading libraries, studying in the vaccination facts, and modifying “New York State” to just “New York” in the facts frame.


facts_url <- "https://github.com/owid/covid-19-data/raw/master/public/data/vaccinations/us_state_vaccinations.csv"

all_facts <- read.csv(data_url)
all_facts$area[all_facts$area == "New York Point out"] <- "New York"

Subsequent, I generate a vector of entries that are not US states or DC. I’ll use it to filter out that facts so my chart doesn’t have far too quite a few rows. 

not_states_or_dc <- c("American Samoa", "Bureau of Prisons", 
"Dept of Defense", "Federated States of Micronesia", "Guam",
"Indian Well being Svc", "Very long Expression Treatment", "Marshall Islands",
"Northern Mariana Islands", "Puerto Rico", "Republic of Palau",
"United States", "Veterans Well being", "Virgin Islands")

This following code block filters out the non_states_or_dc rows, chooses only the most the latest facts, rounds the per cent vaccinated to 1 decimal place, selects only the state and per cent vaccinated columns, and renames my picked columns to Point out and PctFullyVaccinated.

bar_graph_facts_the latest <- all_data %>%  
filter(date == max(date), !(area %in% not_states_or_dc)) %>%
PctFullyVaccinated = round(men and women_fully_vaccinated_per_hundred, 1)
) %>%
decide on(Point out = area, PctFullyVaccinated)

Develop a fundamental bar graph with ggplot2

Subsequent I’ll generate a fundamental (static) ggplot bar chart of the facts. I use geom_col() for a bar chart, add my possess customary blue bars outlined in black and small concept, established the axis text measurement to 10 factors, and flip the x and y coordinates so it’s simpler to read the state names. 

bar_graph <- ggplot(bar_graph_data_recent, 
aes(x = reorder(Point out, PctFullyVaccinated),
y = PctFullyVaccinated)) +
geom_col(color = "black", fill="#0072B2", measurement = .five) +
concept_small() +
concept(axis.text=factor_text(measurement = 10)) +
labs(title = "Percent Thoroughly Vaccinated July 2021",
subtitle = "Knowledge from Our Entire world in Knowledge GitHub repo"
) +
ylab("") +
xlab("") +


Bar chart of state vaccination data Sharon Machlis, IDG

Bar chart of US vaccination facts by state established with ggplot2. Knowledge from Our Entire world in Knowledge.

Develop a tooltip column in R

ggiraph only lets me use 1 column for the tooltip exhibit, but I want the two state and level in my tooltip. There’s an straightforward remedy: Include a tooltip column to the facts frame with the two state and level in 1 text string:

bar_graph_facts_the latest <- bar_graph_data_recent %>%
tooltip_text = paste0(toupper(Point out), "n",
PctFullyVaccinated, "%")

Make the bar chart interactive with ggiraph

To generate a ggiraph interactive bar chart, I changed geom_col() to geom_col_interactive() and added tooltip and facts_id to the aes() mapping. I also diminished the measurement of the axis text, because the ggplot measurement finished up currently being far too large.

Then I exhibited the interactive graph object with the girafe() function. You can established the graph width and height with width_svg and height_svg arguments within girafe()

most current_vax_graph <- ggplot(bar_graph_data_recent, 
aes(x = reorder(Point out, PctFullyVaccinated),
y = PctFullyVaccinated,
tooltip = tooltip_text, facts_id = Point out #<<
)) +
geom_col_interactive(color = "black", fill="#0072B2", measurement = .five) + #<<
concept_small() +
concept(axis.text=factor_text(measurement = 6)) + #<<
labs(title = "Percent Thoroughly Vaccinated July 2021",
subtitle = "Knowledge from Our Entire world in Knowledge GitHub repo"
) +
ylab("") +
xlab("") +

girafe(ggobj = most current_vax_graph, width_svg = five, height_svg = 4)

The graph will glance fairly identical to the ggplot variation — but if you operate the code on your own or check out the online video embedded over, you are going to see that you can now hover more than the bars and see underlying facts. 

Bar chart with blue bars and one yellow bar showing a small box with state name and vaccination rate Sharon Machlis, IDG

If you hover more than a bar on a ggiraph graph, the bar is highlighted and you can see a tooltip with underlying facts. Knowledge from Our Entire world in Knowledge.

One particular matter that seriously tends to make ggiraph glow is how straightforward it is to backlink up multiple graphs. To demo that, of course, I’ll need to have a 2nd visualization to backlink to my bar chart.

The code below generates a facts frame with vaccination facts from February fourteen, 2021, and a ggiraph bar chart with that facts.

bar_graph_facts_early <- all_data %>%
filter(date == "2021-02-fourteen", !(area %in% not_states_or_dc)) %>%
organize(men and women_fully_vaccinated_per_hundred) %>%
PctFullyVaccinated = round(men and women_fully_vaccinated_per_hundred, 1),
tooltip_text = paste0(toupper(area), "n", PctFullyVaccinated, "%")
) %>%
decide on(Point out = area, PctFullyVaccinated, tooltip_text)

early_vax_graph <- ggplot(bar_graph_data_early, aes(x = reorder(State, PctFullyVaccinated), y = PctFullyVaccinated, tooltip = tooltip_text, data_id = State)) +
geom_col_interactive(color = "black", fill="#0072B2", measurement = .five) +
concept_small() +
concept(axis.text=factor_text(measurement = 6)) +
labs(title = "Thoroughly Vaccinated as of February fourteen, 2021",
subtitle = "Knowledge from Our Entire world in Knowledge"
) +
ylab("") +
xlab("") +

Link interactive graphs with ggiraph

The code to backlink the two graphs is really straightforward. Beneath I use the girafe() function to say I want to print the early_vax_graph additionally the latest_vax_graph and established the canvas width and height. I also add an alternative so when the consumer hovers, the bars transform cyan.

girafe(code = print(early_vax_graph + most current_vax_graph), 
width_svg = eight, height_svg = 4) %>%
girafe_options(opts_hover(css = "fill:cyan"))

Linking the two graphs tends to make it straightforward for users to see what transpired to state rankings between February and July. For example, by hovering more than Alaska in the February graph, the bar for Alaska in the July graph also turns cyan. (Without having that alternative, the bars would transform the default yellow color.)

2 bar charts side by side with bars for Alaska highlighted in both. Sharon Machlis, IDG

Hovering more than a state’s bar in 1 graph highlights that state’s bars on the two graphs. Knowledge from Our Entire world in Knowledge.

Link a map and bar chart with ggiraph

This notion will come from Kyle E. Walker, who coded a demo applying his tidycensus offer to generate a map connected with a chart. We can do the same with this facts and a map from scratch applying the albersusa offer (whilst I highly recommend tidycensus if you’re doing the job with U.S. Census facts).

Beneath is the code for the map. us_sf is an R straightforward attributes geospatial object established with the albersusa::usa_sf() function. state_map creates a ggiraph map object from that us_sf object. The map code makes use of typical ggplot() syntax, but in its place of geom_sf() it makes use of geom_sf_interactive(). There are also tooltip and facts_id arguments in the aes() mapping. Ultimately, the code eradicates any history or axes with concept_void().

us_sf <- usa_sf("lcc") %>%
mutate(Point out = as.character(name))

state_map <- ggplot() +
geom_sf_interactive(facts = us_sf, measurement = .125,
aes(facts_id = Point out, tooltip = Point out)) +

The following code block makes use of girafe() and its ggobj argument to exhibit the two the map and the vax graph, connected interactively.

girafe(ggobj = state_map + most current_vax_graph, 
width_svg = 10, height_svg = five) %>%
girafe_options(opts_hover(css = "fill:cyan"))

Now if I hover more than a state on the map, its bar “lights up” on the bar chart.

Map next to a bar chart. New York State is highlighted on both the map and bar chart. Sharon Machlis, IDG

Hover more than a state on the map, and its corresponding bar “lights up” on the bar chart. Knowledge from Our Entire world in Knowledge.

It takes extremely small R code to make a static graphic interactive and to backlink two graphs with each other.

How to use your ggiraph facts visualizations

You can add ggiraph visualizations to an R Markdown doc and make an HTML file that operates in any website browser.

You can also save output from the girafe() function as an HTML widget and then save the widget to an HTML file applying the htmlwidgets offer. For example:  

my_widget <- girafe(ggobj = state_map + latest_vax_graph, 
width_svg = 10, height_svg = five) %>%
girafe_options(opts_hover(css = "fill:cyan"))

htmlwidgets::saveWidget(my_widget, "my_widget_webpage.html",
selfcontained = Accurate)

For more on ggiraph, look at out the ggiraph offer web site.

And for more R tips, head to the InfoWorld Do A lot more With R webpage.

Copyright © 2021 IDG Communications, Inc.

Rosa G. Rose

Next Post

The Top 30 Vulnerabilities Include Plenty of Usual Suspects

Sun Aug 1 , 2021
This 7 days, WIRED described on an alarming phenomenon of authentic warships obtaining their destinations faked by some unfamiliar miscreant. About the final many months, dozens of vessels have appeared to cross into disputed waters when they were being in reality hundreds of miles away. The misinformation has arrive in […]