This post explains how to customize the tooltip in a plotly chart in R. It provides reproducible code and explanation how to improve the default tooltip.
First, we need to load a few packages:
viridis
for the color palettegapminder
for the datasetdplyr
for data manipulation
The gapminder
dataset is used in this example. It
contains data about life expectancy, population and GDP per capita for
many countries over time.
Here, we:
p = data %>%
ggplot( aes(x=gdpPercap, y=lifeExp, size = pop, color = continent)) +
geom_point(alpha=0.7) +
scale_size(range = c(1.4, 19), name="Population (M)") +
scale_color_viridis(discrete=TRUE, guide=FALSE) +
theme_ipsum() +
theme(legend.position="none")
# turn ggplot interactive with plotly
pp = ggplotly(p)
# save the widget
#library(htmlwidgets)
#saveWidget(pp, file="HtmlWidget/plotlyDefaultTooltip.html")
As you can see, it’s a bit unfortunate that the tooltip does not tell us what is the country. Let’s customize it to add this information.
For this, we:
text
in the
dataset that contains the
information we want to display in the tooltip using
the mutate()
function
text
as an aesthetic in the
ggplot()
function
And that’s it!
data = data %>%
mutate(text = paste(
"Country: ", country,
"\nPopulation (M): ", pop,
"\nLife Expectancy: ", lifeExp,
"\nGdp per capita: ", gdpPercap, sep="")
)
p = data %>%
ggplot( aes(x=gdpPercap, y=lifeExp, size=pop, color=continent, text=text)) +
geom_point(alpha=0.7) +
scale_size(range = c(1.4, 19), name="Population (M)") +
scale_color_viridis(discrete=TRUE, guide=FALSE) +
theme_ipsum() +
theme(legend.position="none")
# turn ggplot interactive with plotly
pp = ggplotly(p, tooltip="text")
# save the widget
#library(htmlwidgets)
#saveWidget(pp, file="HtmlWidget/plotlyDefaultTooltip2.html")
The previous example is a good start, but we can go further. Here, we:
round()
function to make the numbers more
readable
data <- data %>%
mutate(text = paste(
"<span style='font-size:16px;'><b>", country, "</b></span><br>",
"<br><b>Population (M):</b> ", pop,
"<br><b>Life Expectancy (years):</b> ", round(lifeExp, 2),
"<br><b>Gdp per capita:</b> $", round(gdpPercap, 2),
sep=""))
p <- data %>%
ggplot(aes(x=gdpPercap, y=lifeExp, size=pop, color=continent, text=text)) +
geom_point(alpha=0.7) +
scale_size(range = c(1.4, 19), name="Population (M)") +
scale_color_viridis(discrete=TRUE, guide=FALSE) +
theme_ipsum() +
theme(legend.position="none")
pp <- ggplotly(p, tooltip="text")
pp <- pp %>%
layout(
hoverlabel = list(bgcolor = "white",
font = list(size = 12, color = "black"))
)
# save the widget
#library(htmlwidgets)
#saveWidget(pp, file="HtmlWidget/plotlyDefaultTooltip3.html")
This post explains how to customize the tooltip in a plotly chart in R.
You can learn more about interactive charts on the R graph gallery.
👋 After crafting hundreds of R charts over 12 years, I've distilled my top 10 tips and tricks. Receive them via email! One insight per day for the next 10 days! 🔥