A quick introduction

The ggiraph package let R users to make ggplot interactive. The package is an htmlwidget. Below an example:

It extends ggplot2 with new geom functions:

These understand three aesthetics to let you add interactivity:

Let’s prepare a ggplot object with mpg dataset.

library(ggiraph)

head(mpg)
## # A tibble: 6 × 11
##   manufacturer model displ  year   cyl      trans   drv   cty   hwy    fl
##          <chr> <chr> <dbl> <int> <int>      <chr> <chr> <int> <int> <chr>
## 1         audi    a4   1.8  1999     4   auto(l5)     f    18    29     p
## 2         audi    a4   1.8  1999     4 manual(m5)     f    21    29     p
## 3         audi    a4   2.0  2008     4 manual(m6)     f    20    31     p
## 4         audi    a4   2.0  2008     4   auto(av)     f    21    30     p
## 5         audi    a4   2.8  1999     6   auto(l5)     f    16    26     p
## 6         audi    a4   2.8  1999     6 manual(m5)     f    18    26     p
## # ... with 1 more variables: class <chr>
g <- ggplot(mpg, aes( x = displ, y = cty, color = hwy) ) + theme_minimal()

tooltips

The first example show how to add tooltip:

my_gg <- g + geom_point_interactive(aes(tooltip = model), size = 2) 
ggiraph(code = print(my_gg), width = .7)

hover effects

Now let’s add an hover effect. Elements associated with a data_id will be animated when mouse will be hover.

my_gg <- g + geom_point_interactive(
    aes(tooltip = model, data_id = model), size = 2) 
ggiraph(code = print(my_gg), width = .7, hover_css = "cursor:pointer;fill:red;stroke:red;")

Default value of hover css is hover_css = "fill:orange;". To see how to change that, read the custome_effects vignette.

Note that data-id can also be reused within a shiny application.

Click actions

Click actions must be a string column in the dataset containing valid javascript instructions.

crimes <- data.frame(state = tolower(rownames(USArrests)), USArrests)
head(crimes)
##                 state Murder Assault UrbanPop Rape
## Alabama       alabama   13.2     236       58 21.2
## Alaska         alaska   10.0     263       48 44.5
## Arizona       arizona    8.1     294       80 31.0
## Arkansas     arkansas    8.8     190       50 19.5
## California california    9.0     276       91 40.6
## Colorado     colorado    7.9     204       78 38.7
# create an 'onclick' column
crimes$onclick <- sprintf("window.open(\"%s%s\")",
  "http://en.wikipedia.org/wiki/", as.character(crimes$state) )

gg_crime <- ggplot(crimes, aes(x = Murder, y = Assault, color = UrbanPop )) + 
  geom_point_interactive(
    aes( data_id = state, tooltip = state, onclick = onclick ), size = 3 ) + 
  scale_colour_gradient(low = "#999999", high = "#FF3333") + 
  theme_minimal()

ggiraph(code = print(gg_crime),
        hover_css = "fill-opacity:.3;cursor:pointer;")