如何使ggplotly显示geom_rect系列的悬停工具提示? [英] How can I make ggplotly show hover tooltips for a geom_rect series?

查看:65
本文介绍了如何使ggplotly显示geom_rect系列的悬停工具提示?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个交互式的可视化图像,以了解多个雇主的个人薪资增长情况.我正在使用geom_rect系列显示工资期和工资信息.当我应用ggplotly函数时,默认情况下不会显示悬停工具提示,并且我找不到启用它们的方法.

我该怎么做才能在geom_rect上启用工具提示?

数据:

  df<-data.frame(来自"= seq(as.Date("2016-01-01""),as.Date("2026-01-01"),乘以14),至"= seq(as.Date("2016-01-01""),as.Date("2026-01-01"),乘以14)+13,雇主"= c(rep(现任雇主",130),rep(未来雇主",131)),工资"= seq(50000,250000,length.out = 261)) 

可见:

 库(ggplot2)图书馆(dplyr)图书馆(密谋)ggplotly(ggplot(数据= df)+geom_rect(aes(xmin = From,xmax = To,ymin =雇主,ymax =雇主,颜色=雇主,大小=薪水))) 

输出(无悬停文字):

请注意,我还问过

I am trying to create an interactive visualisation of an individual's salary growth across multiple employers. I am using a geom_rect series to show pay periods and salary information. When I apply the ggplotly function, hover tooltips are not showing by default, and I cannot find a way to enable them.

What can I do to enable tooltips over the geom_rect?

data:

df <- data.frame(
"From" = seq(as.Date("2016-01-01"), as.Date("2026-01-01"), by = 14),
"To" = seq(as.Date("2016-01-01"), as.Date("2026-01-01"), by = 14)+13,
"Employer" = c(rep("Current employer",130),rep("Future employer",131)),
"Salary" = seq(50000,250000,length.out = 261)
)

vis:

library(ggplot2)
library(dplyr)
library(plotly)
ggplotly(
ggplot(data = df) +
  geom_rect(aes(xmin = From, xmax = To,
                ymin = Employer, ymax = Employer,
                colour = Employer,
                size = Salary))
)

Output (no hover text):

Please note I have also asked a related question on the application of a rangeslider to this problem.

解决方案

In this case geom_rect() is an special aesthetic element compared to classic plotly elements like dots or bars. That is why even enabling tooltip you can not get them. You would need to create the labels such that they can be recognized as known elements for ggplotly() like those mentioned initially. Here the code:

library(ggplot2)
library(dplyr)
library(plotly)
#Code
ggplotly(ggplot(data = df) +
  geom_rect(aes(xmin = From, xmax = To,
                  ymin = Employer, ymax = Employer,
                  colour = Employer,
                  size = Salary))+
  geom_line(aes(x = From,
                y = Employer,
                group = 1,
                text = paste("Date: ",
                             From, "<br>Salary: ", Salary)),
            color='transparent') + 
  geom_point(aes(x = From,
                 y = Employer,
                 text = paste("Date: ", From, "<br>Salary: ",
                              Salary)),
             color='transparent'),tooltip = 'text')

Output:

这篇关于如何使ggplotly显示geom_rect系列的悬停工具提示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆