如何为包含两个(或更多)几何对象的 ggplotly() 对象自定义悬停文本?
问题:
当我将鼠标悬停在该点上时,如下所示的悬停文本不会显示正确的“mean_mpg:”:
我还没有深入研究 ggplotly() 的源代码,但我认为当 ggplotly 生成悬停文本时,它正在寻找美学“x”和“y”,并且它找到了两个几何中指定的“x”和“y”,但由于某种原因,它错误地用“mpg”值更新了“mean_mpg:”值。
我希望能够为我的代表中的每个几何对象单独自定义悬停文本(例如 geom_col()
和 geom_point()
),以便我可以显示正确的值。
非常感谢仍然可以使用ggplotly()
的解决方案,因为我拥有的真实图表要复杂得多。不过,plot_ly()
解决方案也受到赞赏,因为这可能会让我更深入地了解根本问题。
Reprex:
library(ggplot2)
library(dplyr)
library(plotly)
grouped_data <- mtcars %>%
group_by(gear) %>%
mutate(mean_mpg = mean(mpg)) %>%
ungroup()
plot <- ggplot(grouped_data %>%
distinct(gear, mean_mpg, .keep_all = TRUE),
aes(x = gear,
y = mean_mpg)) +
geom_col() +
geom_point(data = grouped_data, aes(x = gear, y = mpg))
ggplotly(plot)
Issue:
The hovertext as shown below doesn't display the correct "mean_mpg:" when I hover over the point:
It should read instead what is displayed correctly when I hover over the bar itself:
I haven't dug deeply into the source code of ggplotly()
, but I think when ggplotly is generating the hovertext, it's looking for the aesthetics "x" and "y", and it's finding "x" and "y" specified in both geoms, but for some reason it's incorrectly updating the "mean_mpg:" value with the "mpg" value.
I would like to be able to customize the hovertext separately for each of the geoms in my reprex (e.g. geom_col()
and geom_point()
) so I can display the correct values.
Would greatly appreciate a solution that still works with ggplotly()
, as the real graph I have is much more complex. However plot_ly()
solutions are also appreciated as that will likely give me greater insight into the underlying issue(s).
Reprex:
library(ggplot2)
library(dplyr)
library(plotly)
grouped_data <- mtcars %>%
group_by(gear) %>%
mutate(mean_mpg = mean(mpg)) %>%
ungroup()
plot <- ggplot(grouped_data %>%
distinct(gear, mean_mpg, .keep_all = TRUE),
aes(x = gear,
y = mean_mpg)) +
geom_col() +
geom_point(data = grouped_data, aes(x = gear, y = mpg))
ggplotly(plot)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不知道为什么,但是:
geom_point(data = grouped_data, aes(x = gear, y = mpg,label=mean_mpg))
给出了所需的结果,但抛出了一条警告消息。
I dont know why but:
geom_point(data = grouped_data, aes(x = gear, y = mpg,label=mean_mpg))
gives the desired result but thorws a warning message.