Reputation: 2293
I have two Plotly plots. I create a subplot to put them together. I would like to link them, such that highlighting a point in either panel also highlights the corresponding points in another panel. This is easy to do when the the plots are built from the same data frame. But what if the plots are built from different data frames -- data frames that share a common ID variable? Can it be done then?
Here is a minimal example. (I am using the Plotly through R, but my question is general to any version of Plotly.) The example is based on the "iris" dataset and uses Species
as the common variable:
library(dplyr) # for %>%, group_by(), mutate(), slice()
library(plotly)
data(iris)
iris1 <- iris %>%
group_by(Species) %>%
mutate(PL = mean(Petal.Length), PW = mean(Petal.Width)) %>%
highlight_key(~Species)
iris2 <- iris1$data() %>%
slice(1) %>% # keep only first row for each species
highlight_key(~Species)
fig1 <- plot_ly(
x = ~Petal.Length,
y = ~Petal.Width,
type = "scatter",
mode = "markers",
color = ~Species,
data = iris1)
fig2 <- plot_ly(
x = ~PL,
y = ~PW,
type = "scatter",
mode = "markers",
color = ~Species,
data = iris2)
subplot(fig1, fig2)
This code produces a two-panel figure. The left-hand panel contains many points, and the different colors of the points represent different species of irises. The right-hand panel contains only three points: one for each species of iris.
The highlighting behavior in this figure isn't what I want. Clicking on a point in either panel highlights a point in the right-hand panel, which is good. But clicking on a point in the right-hand panel doesn't highlight the corresponding points in the left-hand panel.
If fig1
and fig2
were built from the same dataset, there would be no problem. But given that they're built from different datasets, I don't see a way to implement highlighting across the figures -- even though I want highlighting to be based on the Species
variable, which exists in both datasets. Is there a way?
I've looked in SO and at the issues in the Plotly Github repositories, but I haven't seen anything speaking to this point.
Upvotes: 2
Views: 1352
Reputation: 2293
It turns out that the solution is not difficult. There are two keys:
plot_ly()
, but add markers later with add_markers()
.slice()
.Here is code that does the job:
library(dplyr) # for %>%, group_by(), mutate(), slice()
library(plotly)
data(iris)
iris1 <- iris %>%
group_by(Species) %>%
mutate(PL = mean(Petal.Length), PW = mean(Petal.Width)) %>%
highlight_key(~Species)
fig1 <- plot_ly(
x = ~Petal.Length,
y = ~Petal.Width,
type = "scatter",
mode = "markers",
color = ~Species,
data = iris1)
fig2 <- plot_ly(data = iris1) %>% # initiate plot with same data frame
slice(1) %>% # use dplyr verb on plotly object
add_markers(
x = ~PL,
y = ~PW,
color = ~Species)
subplot(fig1, fig2)
I found the solution through Chapter 16 of Carson Sievert's book on Plotly and R, which is quite good.
Upvotes: 2