Interactive scatter plots in R, overlay/hover summary/tooltip as user supplied plot function

泪湿孤枕 提交于 2019-11-30 22:15:28

If you use the latest development version of rbokeh, you can achieve what you are after with the following:

devtools::install_github("bokeh/rbokeh@v0.6.3")

library(rbokeh)

iris$sw <- paste0(iris$Sepal.Width * 20, "px")
iris$pw <- paste0(iris$Petal.Width * 20, "px")
iris$sl <- paste0(iris$Sepal.Length * 20, "px")
iris$pl <- paste0(iris$Petal.Width * 20, "px")

style_str <- "white-space: nowrap; border: 1px solid white; background: steelblue; height: 15px;"

figure() %>%
  ly_points(x = Sepal.Width, y = Sepal.Length, color = Species,
  data = iris, hover = glue::glue("
<div>
  <div style='{style_str} width: @sw'>Sepal width</div>
  <div style='{style_str} width: @pw'>Petal Width</div>
  <div style='{style_str} width: @sl'>Sepal width</div>
  <div style='{style_str} width: @pl'>Petal Length</div>
</div>
"))

What is happening here is rbokeh allows you to specify arbitrary html as tooltips, so here we are creating divs with a specified width according to the data values (referenced with @sw, etc.) to create a bar chart.

The above example works well for a simple bar chart, but if you want to be able to show arbitrary images in a tooltip, one approach would be pre-generate a raster image for each data point and embed that as an html tooltip (an img tag with the base64-encoded image as the src).

If you're using RStudio, the plotly package should be friendly enough to use. For instance:

library(ggplot2)
library(plotly) 
p <- ggplot(iris, aes(Sepal.Length, Petal.Length, colour=Species)) + geom_point()
 ggplotly(p)

The information displayed when hover upon one point looks like:

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