Formatting mouse over labels in plotly when using ggplotly

こ雲淡風輕ζ 提交于 2019-11-27 00:37:18

问题


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?


回答1:


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))



回答2:


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



回答3:


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))


来源:https://stackoverflow.com/questions/34605919/formatting-mouse-over-labels-in-plotly-when-using-ggplotly

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!