# add interactive maps to a ggplot -------
library(ggplot2)
library(ggiraph)
crimes <- data.frame(state = tolower(rownames(USArrests)), USArrests)
# create tooltips and onclick events
states_ <- sprintf("%s",
as.character(crimes$state) )
table_ <- paste0(
"UrbanPop",
sprintf("%.0f", crimes$UrbanPop),
"",
"Assault",
sprintf("%.0f", crimes$Assault),
""
)
onclick <- sprintf(
"window.open(\"%s%s\")",
"http://en.wikipedia.org/wiki/",
as.character(crimes$state)
)
crimes$labs <- paste0(states_, table_)
crimes$onclick = onclick
if (require("maps") ) {
states_map <- map_data("state")
gg_map <- ggplot(crimes, aes(map_id = state))
gg_map <- gg_map + geom_map_interactive(aes(
fill = Murder,
tooltip = labs,
data_id = state,
onclick = onclick
),
map = states_map) +
expand_limits(x = states_map$long, y = states_map$lat)
x <- girafe(ggobj = gg_map)
if( interactive() ) print(x)
}
Run the code above in your browser using DataLab