使用R和ggplot2语法向plot添加自定义工具提示



我正在尝试使用ggplot对象从R创建一个plot plot,该对象具有自定义标签。

#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

我希望特定数据点的值将取自labels,并且仅在数据点悬停时显示

我一直在看同样的问题,我认为你需要做的是这样的(通过https://stackoverflow.com/a/27007513/829256和h/t @plotlygraphs在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

因此,绘图现在应该有一个来自'labels'的值,用于每个数据点,鼠标悬停时显示为工具提示。

您可能想要在如何给点分配标签时做一些更聪明的事情,但希望这能让您开始。

谢谢,我想解决这个问题也会帮助我解决我自己的任务:-)

最新更新