问题
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.
回答1:
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:
来源:https://stackoverflow.com/questions/65270889/how-can-i-make-ggplotly-show-hover-tooltips-for-a-geom-rect-series