In my example, I am trying to create an interactive graph so that a student can view their upcoming assignments.
I need to be able to create a graph in ggplot and then pipe it through ggplotly and/or using style so that hover feature can be used.
My issue is that when I use "style", the hover text does not actually correspond to the correct point. It is most clear when you look at the "Days Until Due" and you see on the graph it will show 5, but the hover text says 30 (picture included for reference).
**This Issue is corrected if I take away my aesthetic for "colour = Priority", however I would like to still be able to use aesthetics.
Bottom Line: How can I create hover text for ggplot2 with custom text while using aesthetics?
#Creating the Dataframe
Priority <- c("High","High","Low","Medium","Low")
Days_Until_Due <- c(30, 28, 5, 15, 1)
Subject <- c("History", "English","English","Math","History")
Assignment_ID <- c("hs12","eng23","en25","mat7","hs33")
df <- data.frame(Priority, Days_Until_Due, Subject, Assignment_ID)
#Creating the Graph
agenda <- df %>%
ggplot(data = ., aes(x= Assignment_ID, y=Days_Until_Due, colour=Priority)) + geom_point() +
xlab("Assignment") + ylab("Days Until Due")
#Creating Labels for Hover Text
labels <- paste("Priority:", df$Priority,
"<br>",
"Days Until Due:",df$Days_Until_Due,
"<br>",
"Subject:",df$Subject,
"<br>",
"ID:",df$Assignment_ID)
#Using Style to create Graph with Hover Text
style(agenda, text = labels)
#using ggplotly and then style (returns the exact same thing as above)
ggplotly(agenda) %>% style(text= labels)
I am brand new to ggplotly and interactive graphs -> any tips are greatly appreciated. Thank you in advance.
The issue is that you assign the wrong labels to your points. To prevent that I would suggest to pass the tooltip texts via the text
attribute or "aesthetic":
library(plotly, warn = FALSE)
df$labels <- paste(
"Priority:", df$Priority,
"<br>",
"Days Until Due:", df$Days_Until_Due,
"<br>",
"Subject:", df$Subject,
"<br>",
"ID:", df$Assignment_ID
)
agenda <- df %>%
ggplot(data = ., aes(x = Assignment_ID, y = Days_Until_Due,
colour = Priority, text = labels)) +
geom_point() +
xlab("Assignment") +
ylab("Days Until Due")
ggplotly(tooltip = "text")