How to choose variable to display in tooltip when using ggplotly?
我有一个简单的数据框:
1 2 3 4 | seq <- 1:10 name <- c(paste0("company",1:10)) value <- c(250,125,50,40,40,30,20,20,10,10) d <- data.frame(seq,name,value) |
我想这样绘制:
1 2 | require(ggplot2) ggplot(data = d,aes(x=seq,y=value))+geom_line() + geom_point() |
现在,我想使用plotly,主要是在将鼠标悬停在某个点上时能够获取除值之外的其他信息,例如公司名称。 我尝试这样:
1 2 | require(plotly) ggplotly() |
这给了我一个工具提示,但只有序列和值。 我尝试了选项tooltip =,但它指定了您只能使用美学中的describe变量,并且在我的aes中不使用名称。
有什么办法吗? 我看到我不是第一个遇到此问题的人,但是我没有找到使用ggplotly的答案。
您不需要按照@ royr2的建议修改
1 | ggplot(data = d, aes(x = seq, y = value, label = name)) + geom_line() + geom_point() |
除
The default,"all", means show all the aesthetic mappings (including the unofficial"text" aesthetic).
因此,只要您不希望将
顺便说一句:我也尝试过
1 | ggplot(data = d, aes(x = seq, y = value, text = name)) + geom_line() + geom_point() |
但随后
geom_path: Each group consists of only one observation. Do you need to adjust the group aesthetic?
并只绘制点。我必须向
1 | ggplot(data = d, aes(x = seq, y = value, text = name)) + geom_line(group = 1) + geom_point() |
(但是请注意,如果您将虚拟组作为第四审美放在
但是,我发现,如果要使用
编辑以回答评论中的问题:
以@UweBlock的答案为基础,您还可以创建虚拟美学,以便在工具提示中显示多个标签。我找不到该文件的记录位置,但却发现了它。虚拟变量会按照您指定的顺序显示,但优先级将赋予默认变量(例如x和y)。为了解决这个问题,您可以在单独的外观中指定这些变量,如下所示:
1 2 3 4 | library(plotly) p = ggplot(iris, aes(label=Species, label2=Petal.Length, label3=Petal.Width)) + geom_point(aes(Sepal.Length,Sepal.Width)) ggplotly(p) |
非官方的
1 2 3 4 5 6 7 8 9 | require(ggplot2) ggplot(data = d,aes(x = seq, y = value, group = 1, text = paste('name: ', name, '</br>name_again: ', name) ))+ geom_line() + geom_point() |
我必须为
最后,我选择了要在工具提示中显示的内容(此处排除了
1 2 | require(plotly) ggplotly(, tooltip = c("x","y","text")) |
您必须修改
编辑:
随着
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | seq <- 1:10 name <- c(paste0("company",1:10)) value <- c(250,125,50,40,40,30,20,20,10,10) d <- data.frame(seq,name,value) require(plotly) gg <- ggplot(data = d,aes(x=seq,y=value))+geom_line() + geom_point() gg <- plotly_build(gg) #OLD: gg$data[[1]]$text <- paste("Seq:", d$seq,"", "Value:", d$value,"", "Company:", d$name) #UPDATED: #Plotly_build creates two separate traces: #One with mode = markers and the other with mode = lines #Hence modify text for the second trace gg$x$data[[2]]$text <- paste("Seq:", d$seq,"", "Value:", d$value,"", "Company:", d$name) gg |