I am making a plot in plotly
using data on aggreagreted demographic groups. I want the user to be able to control what groups and what time periods are shown so I am also using crosstalk
.
I want the lines to visually indicate what kind of data is shown, so data on the entire population is a solid line with no markers, different age groups have different line types and no markers, while men and women have solid lines but different markers. I can’t achieve having no markers for all data execpt the data shown for men and women respectively. Here is what my attempt looks like:
library(plotly)
library(crosstalk)
library(dplyr)
df <- data.frame(
value = runif(15, min = -1, max = 1),
time = rep(c(1, 2, 3), 5),
group = rep(c(1, 2, 3, 4, 5), each = 3),
sex = c(rep(c('Male', 'Female'), each = 3), rep('All', 9)),
age = c(rep('All', 9), rep(c('Young', 'Old'), each = 3))
) %>%
mutate(type = case_when(sex != 'All' ~ sex, age != 'All' ~ age, T ~ 'All'))
sd <- highlight_key(df)
widgets <- bscols(
filter_slider('ti', 'Time', sd, ~time, round = T),
filter_checkbox('ty', 'Type', sd, ~type)
)
lt <- c('All' = 'solid', 'Young' = 'dash', 'Old' = 'dot')
syms <- c('All' = '', 'Male' = '138', 'Female' = '134')
plot <- plot_ly(sd, x = ~time, y = ~value, mode = 'lines+markers',
type = 'scatter', color = ~group, linetype = ~age, symbol = ~sex,
symbols = syms)
bscols(widgets, plot)
…where I try to remove markers for rows having sex==all
with All == ''
when defining syms
. However, this just results in a warning and then all, old and young gets a circle as marker.
In a purely plotly
context I can get the desired visualization by add_trace
for each group individually:
df_no_markers <- df %>% filter(sex == 'All')
df_with_markers <- df %>% filter(sex != 'All')
plot <- plot_ly(sd) %>%
add_trace(data = df_no_markers, x = ~time, y = ~value, color = ~group,
mode = 'lines', linetype = ~age) %>%
add_trace(data = df_with_markers, x = ~time, y = ~value, color = ~group,
mode = 'lines+markers', linetype = I('solid'), symbol = ~sex, symbols = syms)
…but that disconnects it from the widgets, i.e., then I can’t control which lines are shown using the widgets.