Color legend not consequent in R plotly subplot

Viewed 1176

I want to make a plotly bar chart of two synchronized variables. Origin is visits of individuals to a site where two properties are measured in time. In this example individual "a" visits the site twice.

Bars should display the measurement value, be ordered in time and colored according to tag (not variable!).

Let's create some data first.

# R version 3.4.0
set.seed(123)
df <- data.frame(id=factor(rep(c("a", "b", "c", "a"), each=10)),
                 time=as.POSIXct(1:40, origin="2017-01-01"),
                 var1=abs(rnorm(40)),
                 var2=abs(rnorm(40)))

# > head(df)
#   id                time        var1      var2
# 1  a 2017-01-01 01:00:01 0.005764186 0.1176466
# 2  a 2017-01-01 01:00:02 0.385280401 0.9474746
# 3  a 2017-01-01 01:00:03 0.370660032 0.4905574
# 4  a 2017-01-01 01:00:04 0.644376549 0.2560922
# 5  a 2017-01-01 01:00:05 0.220486562 1.8438620
# 6  a 2017-01-01 01:00:06 0.331781964 0.6519499

Now make two plots of each separate variable, assign to same legend group and hide the legend of the second plot.

library(plotly) # version 4.7.0
p1 <- plot_ly(df, x=~time, y=~var1, color=~id, type="bar",
              legendgroup=~id)
p2 <- plot_ly(df, x=~time, y=~var2, color=~id, type="bar",
              legendgroup=~id, showlegend=FALSE)

Then add both plots to a single plot with shared X axis.

subplot(p1, p2, shareX=TRUE, nrows=2)

I'm not sure how to add an HTML page in an SO question, but the above code should provide a reproducible example. PNGs added below for reference.

All IDs selected in the legend

Looks good, right? But for some reason, the legend "selector" does not work properly. Deselecting "a" only affects plot 1 (unexpected behavior), while deselecting "c" affects both plots (expected).

IDs "a" and "c" deselected from legend

What's going on here? Possible bug, or am I missing something?

I'm aware of ggplotly and could get similar plot by using facets. The problem there is that I cannot output a ggplotly HTML that scales with page width (at least not to my knowledge). I want the resulting image to be an HTML that scales with the browser window, which is what plotly does by default.

1 Answers
Related