Plotting a graph with two series obtained by using crosstalk::filter_select on two different datasets

Hello RStudio community,

It is the first time I post a question so sorry in advance for any mistakes I migth make.

I am working in a Rmarkdown document in which I am trying to use crosstalk to create a ggplot2 graph with two series each displaying data coming from different shareddata object. The idea is to compare graphically the data of two datasets that contain a X and Y variables (to be plotted) and some other classification variables whose value will be selected through the filter_select function of crosstalk.

Here is a reprex with the mcars dataset. While I manage to get it to work when the two series are plotted in different graphs (Alternative 1), I do not manage to combine them succesfully into a single graph (Alternative 2). When I do that, the second serie seem to overwrite the first one and the behaviour of the filters is not the one I would expect. Initially all data is displayed but selecting a value on the filter1 make it dissapear and after that only filter2 seems to do something on the graph.

Am I not understanding the behaviour of the sharedata objects correctly? Is it not possible to combine two series on the same plot when using filters? Thank you for your help.


library(ggplot2)
library(plotly)
library(crosstalk)

library(dplyr)

# Initial data
mtcars1 <- mtcars %>%
  filter (vs==0) %>%
  select (mpg, wt, cyl)

mtcars2 <- mtcars %>%
  filter (vs==1) %>%
  select (mpg, wt, cyl)

# Shared obbjects for crosstalk filters
sd1 <- SharedData$new(mtcars1, group="group1")
sd2 <- SharedData$new(mtcars2, group="group2")

filter1 <- list(
  crosstalk::filter_select("cyl","Cylinders:", sd1, ~cyl, multiple=FALSE)
  )

filter2 <- list(
  crosstalk::filter_select("cyl2","Cylinders:", sd2, ~cyl, multiple=FALSE)
  )

# Alternative 1:
# Each series in a different plot - It works fine, but it is not what i am after
g1 <- ggplot2::ggplot(sd1) +
  geom_point(aes(x=mpg, y=wt), color="red") +
  theme_minimal() +
  labs (title="Graph1", x="mpg", y="wt")
gg1 <- ggplotly(g1)

g2 <- ggplot2::ggplot(sd2) +
  geom_point(aes(x=mpg, y=wt), color="green") +
  theme_minimal() +
  labs (title="Graph2", x="mpg", y="wt")
gg2 <- ggplotly(g2)

crosstalk::bscols(
  widths=c(2,NA,NA,2),
  filter1,
  gg1,
  gg2,
  filter2
)

# Alternative 2:
# Both series in the same plot - It does not work, only the second serie is displayed
g <- ggplot2::ggplot() +
  geom_point(data=sd1, aes(x=mpg, y=wt), color="red") +
  geom_point(data=sd2, aes(x=mpg, y=wt), color="green") +
  theme_minimal() +
  labs (title="Graph comparison", x="mpg", y="wt")

gg <- ggplotly(g)

crosstalk::bscols(
  widths=c(3,NA,3),
  filter1,
  gg,
  filter2
)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.