如何使用Plotly摆脱默认工具提示?
问题描述:
我在使用ggplot一段时间,直到我遇到了Plotly库,并开始将它用于我的情节。我仍然使用ggplot函数来创建绘图,最后使用ggplotly函数来转换它。如何使用Plotly摆脱默认工具提示?
我在图中使用geom_tile和geom_text图层来创建热图。我将geom_tile中的“text”属性设置为我想在工具提示中显示的文本,并在ggplotly函数中传递tooltip =“text”。我想在矩形内显示的文本是使用“标签”属性在geom_text图层中设置的文本。
当绘制图呈现时,我可以分别看到两个工具提示,一个是我在geom_tile文本属性中设置的文本,另一个是在geom_text图层的标签属性中重复文本。
我该如何摆脱最后一个工具提示?
在此先感谢!
这里是我的代码:
gg<-ggplot(dataframe, aes(x=varX,y=varY))+
geom_tile(aes(fill=cm,text=paste("#",casos)))+
geom_text(aes(label=cm,size=casos),family = "arial", color="#111111")+
scale_fill_gradient2(low="#DD3333",mid="#EEEE99",high="#00AA00")+
labs(x="varX",y="varY",fill="CM")+ scale_size(range = c(2.5, 5),guide='none') +
theme(text=element_text(family = "arial", color="#666666", size=11) ,title=element_text(family = "arial", color="#666666", face="bold", size=12), axis.text=element_text(family = "arial", color="#666666", size=9),axis.text.x=element_text(angle=330))
ggplotly(gg, tooltip="text")
答
ggplotly()
会自动创建悬停文字 - 这是它的“神奇”的一部分。要覆盖,您必须使用plotly_build()
。
library(plotly)
library(ggplot2)
gg <- ggplot(mtcars, aes(x = cyl, y = gear)) +
geom_tile(aes(fill = mpg))
pb <- plotly_build(gg)
# check structure of pb with str(pb) and see that the text element is a matrix
mtext <- as.character(seq(1,9,1)))
pb$data[[1]]$text <- matrix(mtext, 3, 3)
pb