简体   繁体   中英

Adding custom tooltip to plotly using R and ggplot2 syntax

I am trying to create a plotly plot from R using a ggplot object, which has custom labels.

#library('devtools')
#install_github("ropensci/plotly")
library('plotly')
set_credentials_file(username="your_name", api_key="your_key")

py <- plotly()
labels = LETTERS[sample(x=26, size=nrow(iris), replace=T)]
ggiris <- ggplot(iris, aes(Petal.Width, Sepal.Length, color = Species)) + geom_point()

r <- py$ggplotly(ggiris)
r$response

I would like that the value for a particular data-point would be taken from labels and would be displayed only when hovering the data-point.

I've been looking at the same problem and I think what you need to do is something like this (via https://stackoverflow.com/a/27007513/829256 and h/t to @plotlygraphs on Twitter)

# first use your Plotly connection and retrieve data for the ggiris plot you uploaded
irisplot <- py$get_figure('username', n)  # where n = the number of this plot on your account

# inspect the irisplot object
str(irisplot)  # a list of 2

# inspect irisplot$data
str(irisplot$data)  # a list of 3, one list for each Species

# overwrite 'text' for each Species list
irisplot$data[[1]]$text <- labels[1:50]
irisplot$data[[2]]$text <- labels[51:100]
irisplot$data[[3]]$text <- labels[101:150]

# re-upload to Plotly
resp <- py$plotly(irisplot$data, kwargs = list(layout = irisplot$layout))

# check out your new plot
resp$url

So the plot should now have a value from 'labels' for each data point, displayed as a tooltip with mouseover.

You will presumably want to do something smarter in how you assign the labels to the points, but hopefully this gets you started.

And thanks, I think working through this question will help me solve my own task too :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM