简体   繁体   English

使用 R 和 ggplot2 语法将自定义工具提示添加到绘图中

[英]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.我正在尝试使用具有自定义标签的 ggplot 对象从 R 创建一个情节图。

#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.我希望特定数据点的值将从labels获取,并且仅在悬停数据点时显示。

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)我一直在研究同样的问题,我认为你需要做的是这样的事情(通过https://stackoverflow.com/a/27007513/829256和 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 :-)谢谢,我认为解决这个问题也将帮助我解决我自己的任务:-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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