I'm working on a project using ggplotly() and am having trouble formatting my hover text. Specifically, I'm using the text aesthetic to format my tooltip, which works great. The problem I'm running into is that I would like to also print the x value at the top of the tooltip a single time, like what occurs when using base {plotly}.
library(tibble)
library(ggplot2)
library(plotly)
# Example dataset
df <- tribble(
~TIME, ~CATEGORY, ~VALUE,
1, "Apple", 7,
1, "Banana", 6,
1, "Cat", 3,
2, "Apple", 10,
2, "Banana", 12,
2, "Cat", 0,
3, "Apple", 23,
3, "Banana", 12,
3, "Cat", 3,
4, "Apple", 23,
4, "Banana", 8,
4, "Cat", 3,
5, "Apple", 9,
5, "Banana", 10,
5, "Cat", 3
)
p <- ggplot(df, aes(x = TIME, y = VALUE, color = CATEGORY,
text = paste0(CATEGORY, " value = ", VALUE))) +
geom_line(group = 1, size = 0.7)
# Convert to plotly with unified x tooltip and custom hovertemplate
ggplotly(p, tooltip = c("text", "x")) %>%
layout(hovermode = "x unified", hoverlabel = list(font = list(family = "Consolas")))

I'm aware that I can utilize a hovertemplate to add back in the default plotly behavior, but this effectively undoes the functionality of being able to use the text aesthetic to format the hover, which is really useful, and also still leaves me with questions regarding formatting the X value itself.
ggplotly(p, tooltip = c("text")) %>%
layout(hovermode = "x unified", hoverlabel = list(font = list(family = "Consolas"))) #%>%
style(hovertemplate = paste0("%{y} Units"))

So, I'm ultimately wondering if there is a way to include that single X value at the top while still being able to utilize the text aesthetic as the tooltip itself. If that's not possible, how can I use hovertemplate and potential other style inputs to format the tooltip like I am currently doing with the text aesthetic.
A bit of a hack, but we can add another trace for TIME but set its color to NA:
p <- ggplot(df) +
geom_line(aes(x = TIME, y = VALUE,
text = paste("TIME:", TIME, "Hours")),
color=NA) +
geom_line(aes(x = TIME, y = VALUE, color = CATEGORY,
text = paste(CATEGORY, "value =", VALUE)),
group = 1, size = 0.7)
ggplotly(p, tooltip = c("text")) %>%
layout(hovermode = "x unified",
hoverlabel = list(font = list(family = "Consolas"))

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With