I have am plotting a bar graph geom with a point geom layered on top of that like so:
plot_1 <- ggplot(results, aes(x=date, y = data, question_text=question_text,
val1 = val1)) +
geom_bar(stat = "identity", position = "dodge", aes(fill = Party)) +
geom_point(data=results, aes(x=date, y=math*.01), colour="blue", group = 1)
I then call the ggplotly command and overlay tooltips like so
ggplotly(plot_1, tooltip=c("question_text", "val1"))
However, this makes it such that, whenever I put my mouse over either a geom_point or a geom_bar, the tooltip pops up. How do I make it such that the tool tip only pops up when overlapping on the bar graphs?
Well I hope you figured this out in the meantime, but I ran into the same issue and thought I'd help anyone else who ends up here.
The key for me was the style()
function. For context, here is a simplistic version of the plot I was trying to make:
p = ggplot(df, aes(x = category, y = total, group = group_level))+
geom_bar(stat = "identity", position = position_dodge(width = .75))+ # Should probably just be using geom_col here
geom_text(label = state)
Without including the style function below, I was getting hover info for both the bars and the text labels which looked a bit silly. The following allows you to choose which traces have hover info (or any "visual property" according to the docs)
ggplotly(p, tooltip = c("text")) %>%
style(hoverinfo = "none", traces = c(3, 4))
Now Plotly's documentation is consistently abysmal, both in structure and comprehensiveness. Figuring out which traces were which was a bit of trial and error, but therein lies the fun.
To expand on @MokeEire's answer, using the style()
function and applying it to specific traces does the trick. I had absolutely no idea how to determine which traces were numbered which, though.
Here's a way to print out your traces in order, describing what kind of geom they map to (requires listviewer
and jsonlite
).
Setting up a ggplotly object with Titanic data:
data(Titanic)
t <- data.frame(Titanic) %>%
group_by(Class, Sex) %>%
summarize(Freq = sum(Freq))
plot1 <- ggplot(t, aes(x=Class, y = Freq)) +
geom_bar(stat = "identity", position = "dodge", aes(fill = Sex)) +
geom_text(aes(label=Freq, group=Sex),
position = position_dodge(width = 1))
p <- ggplotly(plot1)
Printing the traces:
p_json <- plotly_json(p)
print(paste0(fromJSON(p_json$x$data)$data$type, ": ",
fromJSON(p_json$x$data)$data$name))
This returns something like:
"bar: Male" "bar: Female" "scatter: NA"
And you know your bar plot is the 1st and 2nd traces, and the labels ("scatter") are the 3d.
So to remove tool tips for the labels (don't waste an hour forgetting that R is 1-indexed like I did):
ggplotly(p, tooltip = c("text")) %>%
style(hoverinfo = "none", traces = 3)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With