Easily create interactive ggplot graphs in R with ggiraph

Static visualizations are often more than enough to notify stories with your info. But in some cases you want to insert interactivity, so buyers can hover in excess of graphs to see fundamental info or url their hover in excess of 1 visualization to highlighting info in one more. 

R has a number of offers for making interactive graphics together with echarts4r, plotly, and highcharter. I like and use all of individuals. But for easy linking of interactive graphs, it’s tricky to defeat ggiraph.

From ggplot to ggiraph in 3 easy techniques

There are 3 easy techniques to transform ggplot code into an interactive graph:

  1. Use a ggiraph interactive geom instead of a “regular” ggplot geom. The format is easy to bear in mind: Just insert _interactive to your typical geom. So, geom_col() for a typical bar chart would be geom_col_interactive(), geom_stage() would be geom_stage_interactive(), and so on. 
  2. Insert at minimum 1 interactive argument to the graph’s aes() mapping: tooltip, info_id, or onclick. That info_id argument is what connects two graphics, letting you hover in excess of 1 and impact the display screen of one more 1 — all without having Shiny. 
  3. After making your ggiraph dataviz object, use the girafe() function to transform it into a JavaScript graphic. Of course, that is girafe() like the animal but with 1 f. (Which is how you spell it in French, and the creator of ggiraph, David Gohel, life in Paris.)

Put in the R offers

If you’d like to adhere to together with the code in this tutorial, you are going to need to have the ggplot2, ggiraph, dplyr, and patchwork offers from CRAN on your system as nicely as ggiraph. And, to build a map, I’ll be using Bob Rudis’s albersusa package deal, which isn’t on CRAN. You can put in it from GitHub with 

controllers::put in_github("hrbrmstr/albersusa")

or

devtools::put in_github("hrbrmstr/albersusa")

Put together the info

For info, I’m likely to use the latest US Covid vaccination info by point out out there from the Our Globe in Information GitHub repository.

In the code beneath, I’m loading libraries, examining in the vaccination info, and changing “New York State” to just “New York” in the info frame.

library(dplyr)
library(ggplot2)
library(ggiraph)
library(patchwork)

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

all_info <- read.csv(data_url)
all_info$location[all_info$location == "New York State"] <- "New York"

Next, I build a vector of entries that aren’t US states or DC. I’ll use it to filter out that info so my chart does not have too many rows. 

not_states_or_dc <- c("American Samoa", "Bureau of Prisons", 
"Dept of Protection", "Federated States of Micronesia", "Guam",
"Indian Health and fitness Svc", "Extensive Expression Treatment", "Marshall Islands",
"Northern Mariana Islands", "Puerto Rico", "Republic of Palau",
"United States", "Veterans Health and fitness", "Virgin Islands")

This upcoming code block filters out the non_states_or_dc rows, chooses only the most the latest info, rounds the percent vaccinated to 1 decimal stage, selects only the point out and percent vaccinated columns, and renames my chosen columns to State and PctFullyVaccinated.

bar_graph_info_the latest <- all_data %>%  
filter(date == max(date), !(location %in% not_states_or_dc)) %>%
mutate(
PctFullyVaccinated = spherical(people today_fully_vaccinated_for every_hundred, 1)
) %>%
find(State = location, PctFullyVaccinated)

Produce a essential bar graph with ggplot2

Next I’ll build a essential (static) ggplot bar chart of the info. I use geom_col() for a bar chart, insert my individual customary blue bars outlined in black and negligible concept, set the axis text dimension to ten points, and flip the x and y coordinates so it’s less complicated to study the point out names. 

bar_graph <- ggplot(bar_graph_data_recent, 
aes(x = reorder(State, PctFullyVaccinated),
y = PctFullyVaccinated)) +
geom_col(shade = "black", fill="#0072B2", dimension = .5) +
concept_negligible() +
concept(axis.text=aspect_text(dimension = ten)) +
labs(title = "Percent Fully Vaccinated July 2021",
subtitle = "Information from Our Globe in Information GitHub repo"
) +
ylab("") +
xlab("") +
coord_flip()

bar_graph

Bar chart of state vaccination data Sharon Machlis, IDG

Bar chart of US vaccination info by point out developed with ggplot2. Information from Our Globe in Information.

Produce a tooltip column in R

ggiraph only lets me use 1 column for the tooltip display screen, but I want both point out and amount in my tooltip. There is an easy option: Insert a tooltip column to the info frame with both point out and amount in 1 text string:

bar_graph_info_the latest <- bar_graph_data_recent %>%
mutate(
tooltip_text = paste0(toupper(State), "n",
PctFullyVaccinated, "%")
)

Make the bar chart interactive with ggiraph

To build a ggiraph interactive bar chart, I changed geom_col() to geom_col_interactive() and added tooltip and info_id to the aes() mapping. I also reduced the dimension of the axis text, mainly because the ggplot dimension ended up remaining too massive.

Then I shown the interactive graph object with the girafe() function. You can set the graph width and top with width_svg and top_svg arguments within girafe()

hottest_vax_graph <- ggplot(bar_graph_data_recent, 
aes(x = reorder(State, PctFullyVaccinated),
y = PctFullyVaccinated,
tooltip = tooltip_text, info_id = State #<<
)) +
geom_col_interactive(shade = "black", fill="#0072B2", dimension = .5) + #<<
concept_negligible() +
concept(axis.text=aspect_text(dimension = six)) + #<<
labs(title = "Percent Fully Vaccinated July 2021",
subtitle = "Information from Our Globe in Information GitHub repo"
) +
ylab("") +
xlab("") +
coord_flip()

girafe(ggobj = hottest_vax_graph, width_svg = 5, top_svg = four)

The graph will glance rather identical to the ggplot model — but if you operate the code oneself or enjoy the movie embedded over, you are going to see that you can now hover in excess of the bars and see fundamental info. 

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 in excess of a bar on a ggiraph graph, the bar is highlighted and you can see a tooltip with fundamental info. Information from Our Globe in Information.

A person point that really helps make ggiraph shine is how easy it is to url up many graphs. To demo that, of course, I’ll need to have a next visualization to url to my bar chart.

The code beneath results in a info frame with vaccination info from February 14, 2021, and a ggiraph bar chart with that info.

bar_graph_info_early <- all_data %>%
filter(date == "2021-02-14", !(location %in% not_states_or_dc)) %>%
organize(people today_fully_vaccinated_for every_hundred) %>%
mutate(
PctFullyVaccinated = spherical(people today_fully_vaccinated_for every_hundred, 1),
tooltip_text = paste0(toupper(location), "n", PctFullyVaccinated, "%")
) %>%
find(State = location, 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(shade = "black", fill="#0072B2", dimension = .5) +
concept_negligible() +
concept(axis.text=aspect_text(dimension = six)) +
labs(title = "Fully Vaccinated as of February 14, 2021",
subtitle = "Information from Our Globe in Information"
) +
ylab("") +
xlab("") +
coord_flip()

Url interactive graphs with ggiraph

The code to url the two graphs is incredibly straightforward. Beneath I use the girafe() function to say I want to print the early_vax_graph moreover the latest_vax_graph and set the canvas width and top. I also insert an choice so when the consumer hovers, the bars transform cyan.

girafe(code = print(early_vax_graph + hottest_vax_graph), 
width_svg = 8, top_svg = four) %>%
girafe_choices(opts_hover(css = "fill:cyan"))

Linking the two graphs helps make it easy for buyers to see what transpired to point out rankings between February and July. For case in point, by hovering in excess of Alaska in the February graph, the bar for Alaska in the July graph also turns cyan. (Without the need of that choice, the bars would transform the default yellow shade.)

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

Hovering in excess of a state’s bar in 1 graph highlights that state’s bars on both graphs. Information from Our Globe in Information.

Url a map and bar chart with ggiraph

This concept arrives from Kyle E. Walker, who coded a demo working with his tidycensus package deal to build a map joined with a chart. We can do the very same with this info and a map from scratch working with the albersusa package deal (though I very endorse tidycensus if you are performing with U.S. Census info).

Beneath is the code for the map. us_sf is an R straightforward characteristics geospatial object developed with the albersusa::united states of america_sf() function. point out_map creates a ggiraph map object from that us_sf object. The map code utilizes normal ggplot() syntax, but instead of geom_sf() it utilizes geom_sf_interactive(). There are also tooltip and info_id arguments in the aes() mapping. Lastly, the code eradicates any track record or axes with concept_void().

library(albersusa)
us_sf <- usa_sf("lcc") %>%
mutate(State = as.character(title))

point out_map <- ggplot() +
geom_sf_interactive(info = us_sf, dimension = .125,
aes(info_id = State, tooltip = State)) +
concept_void()

The upcoming code block utilizes girafe() and its ggobj argument to display screen both the map and the vax graph, joined interactively.

girafe(ggobj = point out_map + hottest_vax_graph, 
width_svg = ten, top_svg = 5) %>%
girafe_choices(opts_hover(css = "fill:cyan"))

Now if I hover in excess of a point out 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 in excess of a point out on the map, and its corresponding bar “lights up” on the bar chart. Information from Our Globe in Information.

It requires quite minimal R code to make a static graphic interactive and to url two graphs collectively.

How to use your ggiraph info visualizations

You can insert ggiraph visualizations to an R Markdown doc and make an HTML file that functions in any web browser.

You can also help save output from the girafe() function as an HTML widget and then help save the widget to an HTML file working with the htmlwidgets package deal. For case in point:  

my_widget <- girafe(ggobj = state_map + latest_vax_graph, 
width_svg = ten, top_svg = 5) %>%
girafe_choices(opts_hover(css = "fill:cyan"))

htmlwidgets::saveWidget(my_widget, "my_widget_page.html",
selfcontained = Legitimate)

For extra on ggiraph, look at out the ggiraph package deal site.

And for extra R tips, head to the InfoWorld Do Much more With R page.

Copyright © 2021 IDG Communications, Inc.