g2r supports crosstalk to link g2 visualisations with other htmlwidgets that supports crosstalk.

Warning

Crosstalk only works with data passed to g2.

Filter

For instance, one can add a g2 plot to an example from the plotly R book.

library(g2r)
library(plotly)
library(crosstalk)

# plotly
tx <- highlight_key(txhousing)

# filter widgets
widgets <- htmltools::div(
  filter_select("city", "Cities", tx, ~city),
  filter_slider("sales", "Sales", tx, ~sales),
  filter_checkbox("year", "Years", tx, ~year, inline = TRUE)
)

# arrange
bscols(
  widths = c(2, 5, 5),
  widgets, 
  plot_ly(tx, x = ~date, y = ~median, showlegend = FALSE) %>% 
    add_lines(color = ~city, colors = "black"),
  g2(tx, asp(date, median, color = city), digits = 16) %>% 
    fig_line() %>% 
    legend_color(FALSE)
)

Select

g2r also supports the select handle so selection is communicated between widgets. Note the use of selected, without which selecting a point on the g2 plot (though works fine crosstalk-wise) does not highlight the stroke in black.

shared_cars <- SharedData$new(cars)

bscols(
  plot_ly(shared_cars, x = ~speed, y = ~dist) %>% 
    add_markers(),
  g2(shared_cars, asp(speed, dist)) %>% 
    fig_point(selected(stroke = "black"))
)

Customisation

The selection handle can be greatly customised to define the look of points, bars, etc when they are selected or unselected. The crosstalk_select function accepts the name of the attribute to change and the values this attribute should take when within selected (on) and outside the selection (off), setting on or off to NULL means not to change that attribute for that state.

df <- data.frame(
  x = letters,
  y = runif(26)
)

sd <- SharedData$new(df)

bscols(
  plot_ly(sd, x = ~x, y = ~y) %>% 
    add_bars(),
  g2(sd, asp(x, y)) %>% 
    fig_interval() %>% 
    crosstalk_select("fill", on = "green", off = "grey") %>% 
    crosstalk_select("stroke", on = "black", off = "grey")
)

One can reproduce the effect given by plotly by playing with the opacity for instance.

bscols(
  plot_ly(sd, x = ~x, y = ~y) %>% 
    add_bars(),
  g2(sd, asp(x, y)) %>% 
    fig_interval() %>% 
    crosstalk_select("fillOpacity", on = 1, off = .3)
)