Reputation: 11762
I am struggling with text formatting when using ggplotly
and the mouse over functionality.
library(plotly)
df <- data.frame(a=letters, b=LETTERS, x=runif(26), y=runif(26))
g <- ggplot(df, aes(x,y)) + geom_point(aes(text=sprintf('letter: %s\nLetter: %s', a, b)))
g
(gg <- ggplotly(g))
I would like to have some formatted text or at least a newline in my mouse over label. Is there a good documentation on how to design this mouse over bubble thing?
Upvotes: 48
Views: 51294
Reputation: 698
Here's a solution using purrr's map function. It kinda surprised me that it worked but I like it.
I bolded the 'letter:' and 'Letter:' headings. This still prints the x-y coordinates, which you can remove with the argument tooltip
in ggplotly()
.
df <- data.frame(a=letters, b=LETTERS, x=runif(26), y=runif(26))
g <- ggplot(df, aes(x,y)) +
geom_point(aes(text=map(paste('<b>letter:</b>', a, '<br>', '<b>Letter:</b>', b), HTML)))
g
(gg <- ggplotly(g))
Upvotes: 1
Reputation: 1461
See the tooltip
argument to ggplotly(). For instance, to show only the species name (e.g. virginica
for the top right point) on hover:
g <- ggplot(tail(iris), aes(Petal.Length, Sepal.Length, text=Species)) + geom_point()
ggplotly(g, tooltip="text")
Other examples:
ggplotly(g, tooltip="x") # Petal.Length: 5.7
ggplotly(g, tooltip="Petal.Length") # Petal.Length: 5.7
ggplotly(g, tooltip=c("x", "y"))
The last example will show the two-line tooltip
Petal.Length: 5.7
Sepal.Length: 6.7
Upvotes: 78
Reputation: 17611
plotly
can make use of the line break HTML tag. You can get what your after using the <br>
tag for a newline:
g <- ggplot(df, aes(x,y)) +
geom_point(aes(text=sprintf("letter: %s<br>Letter: %s", a, b)))
(gg <- ggplotly(g))
Upvotes: 33