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:
Three arguments let you add interactivity:
tooltip
: column of dataset that contains tooltips to be displayed when mouse is over elements.onclick
: column of dataset that contains javascript function to be executed when elements are clicked.data_id
: column of dataset that contains id to be associated with elements.Let’s prepare a ggplot object with mpg
dataset.
library(ggiraph)
head(mpg)
## manufacturer model displ year cyl trans drv cty hwy fl class
## 1 audi a4 1.8 1999 4 auto(l5) f 18 29 p compact
## 2 audi a4 1.8 1999 4 manual(m5) f 21 29 p compact
## 3 audi a4 2.0 2008 4 manual(m6) f 20 31 p compact
## 4 audi a4 2.0 2008 4 auto(av) f 21 30 p compact
## 5 audi a4 2.8 1999 6 auto(l5) f 16 26 p compact
## 6 audi a4 2.8 1999 6 manual(m5) f 18 26 p compact
g <- ggplot(mpg, aes( x = displ, y = cty, color = drv) ) + theme_minimal()
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)
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)
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 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;")
You can activate zoom; set zoom_max
(maximum zoom factor) to a value greater than 1.
ggiraph(code = print(my_gg + theme_linedraw()), zoom_max = 5)