(Based on the "Add Lines" example found here: https://plot.ly/ggplot2/geom_histogram/. It is also similar to this Q, which has no satisfactory anwser for me, since I need to use the ggplot
features, like being able to use log scale in the x-axis)
In a normal plot_ly
plot, when some legend element is clicked, the plot is modified taking away all the cases matching that legend group. The following example illustrates this behaviour:
library(plotly)
gg_color_hue <- function(n) {
hues = seq(15, 375, length = n + 1)
hcl(h = hues, l = 65, c = 100)[1:n]
}
set.seed(0)
df1 <- data.frame(
cond = factor(rep(c("A", "B"), each=200)),
rating = c(rnorm(200), rnorm(200, mean=.9))
)
plot_ly(df1,
x = ~rating,
color = ~cond,
colors = gg_color_hue(2)) %>%
add_histogram() %>%
layout(barmode = "stack")
The figures show the interactive plot before and after clicking on the groups of the legend:
Figure 1: Histogram made using plot_ly
, as it is plotted initially.
Figure 2: Histogram made using plot_ly
, with only the B cases (after the A in the legend was clicked). Note how both axis adjusted to the new range of values.
Figure 3: Histogram made using plot_ly
, with only the A cases (B was clicked). Again, both axis adjusted to the new range of values.
However, this does not happen when the plot is created via ggplot
+ ggplotly
. Here is an example (please, do not mind the change in labels and colors or in the shape of the histograms, since those are not the focus of this Q and I don't believe are relevant):
p <- ggplot(data = df1) +
aes(x = rating, fill = cond) +
geom_histogram(bins = 13)
ggplotly(p)
Figure 4: Histogram made using ggplot
and ggplotly
.
Figure 5: Histogram made using ggplot
and ggplotly
, now with only the B cases (A was clicked). Note that the axis remain unchanged this time.
Figure 6: Histogram made using ggplot
and ggplotly
, now with only the A cases (B was clicked). Clearly the most ridiculous plot of them all, since the bars simply remain in their original spot, which is not helpfull at all for a histogram.
As I said, this is not a very desirable behaviour and I do not know if there's something I can do to correct it. If someone knows what can I do about this, I'll be very thankful.