Formatting mouse over labels in plotly when using ggplotly

戏子无情 提交于 2019-11-28 05:00:01

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

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

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