Any way to display data frame information besides x and y on hover with shiny/ggplot?

倾然丶 夕夏残阳落幕 提交于 2020-01-06 05:59:17

问题


> df <- data.frame(x=c(1,2,3,4,5), y=c(6,7,8,9,10), z=c('a','b','c','d','e'))
> df
  x  y z
1 1  6 a
2 2  7 b
3 3  8 c
4 4  9 d
5 5 10 e

ggplot(df,
  aes(x=x, y=y)+
  geom_point()

Let's say I have a data frame with columns x, y, and z. I create a ggplot with x along the x axis and y along the y axis. I've seen examples of hover code that displays the x and y values when hovering over a point, but is it possible to access other data in the data frame besides what's graphed along x and y? For example if someone hovers over point (1,6), is there a way to display 'a'?


回答1:


You can use the following code based on the plotly package:

df <- data.frame(x=c(1,2,3,4,5), y=c(6,7,8,9,10), z=c('a','b','c','d','e'))

library(ggplot2)
# Define the content and format of the tooltip in the "text" aesthetic
p <- ggplot(df, aes(x=x, y=y, 
           text=paste("X=",x,"<br>Y=",y,"<br>Z=",z))) + 
geom_point()

library(plotly)
p <- ggplotly(p, tooltip="text")
print(p)



来源:https://stackoverflow.com/questions/45612335/any-way-to-display-data-frame-information-besides-x-and-y-on-hover-with-shiny-gg

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!