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

2023-12-04

我正在尝试使用 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

我希望特定数据点的值取自labels并且仅当悬停数据点时才会显示。


我一直在研究同样的问题,我认为你需要做的是这样的事情(通过https://stackoverflow.com/a/27007513/829256以及 Twitter 上的 @plotlygraphs 的 h/t)

# 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

因此,该图现在应该具有每个数据点的“标签”值,并在鼠标悬停时显示为工具提示。

您可能想要在如何将标签分配给点方面做一些更聪明的事情,但希望这可以帮助您开始。

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐