Reputation: 2498
I'm creating a ggplotly for a dataframe that's very similar to diamonds
. Here's what I have so far:
ggplotly(ggplot(diamonds, aes(depth, colour = cut)) +
geom_density() +
xlim(55, 70))
It creates the following:
When you hover over the trace it shows: depth, cut, and density. I want to also show the clarity so I added the following:
ggplotly(ggplot(diamonds, aes(depth, text = paste("Clarity: ", clarity), colour = cut)) +
geom_density() +
xlim(55, 70))
That command creates the following:
When I hover of the curve it shows depth, Clarity, cut, and density. That's what I want. However, how do I keep the density as one curve like how it was in the first plot I created instead of multiple curves?
Upvotes: 0
Views: 469
Reputation: 3087
I realize that this is an old answer, but the main problem here is that you're trying to do something that's logically impossible.
clarity
and cut
are two separate dimensions, so you can't simply put the clarity
in a tooltip on the line that's grouped by cut
, because that line represents diamonds of all different clarity
s grouped together.
Once you add clarity
into the mix (via the text
aesthetic), ggplot rightly separates the various clarities
out, so that it has a clarity
to refer to. You could force it back to grouping just by cut
by adding group=cut
to the aes
, but you'll lose the clarity
tooltip, because there's no meaningful value of clarity
when you're grouping just by cut
- again, each point is all clarities at once.
Richard's solution simply displays both graphs at once, but makes the clarity
-grouped ones invisible. I'm not sure what the original goal was here, but that doesn't accomplish anything useful, because it just lets you mouse-over invisible peaks in addition to the properly-grouped cut
bands.
I'm not sure what your original data was, but you simply can't display two dimensions and group by only one of them. You'd either have to use the multiple curves, which accurately represent the second dimension, or flatten the second dimension by doing some sort of summarization of it - in the case of clarity
, there's not really any sensible summarization you can do, but if it were, say, price, you could display an average.
Upvotes: 0
Reputation: 9923
Does this work? Set the alpha of the extra lines to 0 (so they become transparent. Using geom_line as geom_density uses alpha for fill only. (system problems prevent testing)
ggplotly(
ggplot(diamonds, aes(depth, colour = cut)) +
geom_density() +
geom_line(aes(text = paste("Clarity: ", clarity)), stat="density", alpha=0) +
xlim(55, 70)
)
Upvotes: 1