我正在使用聚合人口群体的数据在
plotly
中绘制一个图。我希望用户能够控制显示哪些组和哪些时间段,所以我也使用 crosstalk
。
我希望线条能够直观地表明显示的数据类型,因此整个人口的数据是一条没有标记的实线,不同年龄组有不同的线型并且没有标记,而男性和女性有实线但不同的标记。除了分别显示的男性和女性数据之外,我无法实现对所有数据都没有标记。这是我的尝试:
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)
...在定义
sex==all
时,我尝试删除具有 All == ''
和 syms
的行的标记。然而,这只会导致警告,然后所有的人,无论老少,都会得到一个圆圈作为标记。
在纯粹的
plotly
上下文中,我可以通过add_trace
为每个组单独获得所需的可视化:
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)
...但这会断开它与小部件的连接,也就是说,我无法控制使用小部件显示哪些行。
您可以通过将性别=所有行的大小设置为零来解决不需要的标记。
plot <- plot_ly(sd, x = ~time, y = ~value, mode = 'lines+markers',
type = 'scatter', color = ~group,
marker = list(size = ~ifelse(sex == "All", 0, 10)),
linetype = ~age, symbol = ~sex,
symbols = symbols)