Last active
April 28, 2022 07:13
-
-
Save matt-dray/8e5d03e32318da90ee53cd35d81871c0 to your computer and use it in GitHub Desktop.
Create custom tooltip text for ggplotly by using a 'text' argument in 'geom_*(aes())'
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(dplyr) | |
library(ggplot2) | |
library(plotly) | |
library(viridis) | |
data("starwars") | |
p <- ggplot(starwars) + | |
geom_point( | |
aes( # all 4 aes() arguments will print in the plotly tooltip | |
x = height, # arg 1 | |
y = mass, # arg 2 | |
colour = gender, # arg 3 | |
text = paste( | |
"This is", name, | |
"\nwho is", height/100, "m tall", | |
"\nand has mass", mass, "kg"), | |
) # arg 4 | |
) + | |
scale_color_viridis(discrete = TRUE) # THINK OF THE COLOURBLIND | |
# You can ignore the warning: | |
# Warning: Ignoring unknown aesthetics: text | |
# Plot with tooltip that contains only the 'text' arg from aes() | |
# View the output here: http://rpubs.com/matt-dray/starwars-ggplotly-tooltip | |
ggplotly(p, tooltip = "text") | |
# Compare to what happens without the specification | |
# ggplotly(p) # all aes() arguments are in the tooltip |
It is a pity this doesn't work for geom_area, not sure why it doesn't. If I use label instead of text in aes() I get a plot, but with mangled tooltip. If I use text as per below, I get no plot and good tooltip.
p <- ggplot(starwars) +
geom_point(
aes( # all 4 aes() arguments will print in the plotly tooltip
x = height, # arg 1
y = mass, # arg 2
colour = gender, # arg 3
text = str_glue(
"This is {name}
who is {height/100} m tall
and has mass {mass} kg"),
) # arg 4
) +
scale_color_viridis(discrete = TRUE) # THINK OF THE COLOURBLIND
p
# You can ignore the warning:
# Warning: Ignoring unknown aesthetics: text
# Plot with tooltip that contains only the 'text' arg from aes()
# View the output here: http://rpubs.com/matt-dray/starwars-ggplotly-tooltip
ggplotly(p, tooltip = "text")
UPDATE:
Fixed, I need to add group in the aes()
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
So clever :-)