Skip to content

Commit edc77b0

Browse files
committed
add "legenditem" property
legenditem allows to group multiply traces into one legend item
1 parent 6d6e3af commit edc77b0

File tree

1 file changed

+13
-1
lines changed

1 file changed

+13
-1
lines changed

R/plotly.R

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -340,7 +340,8 @@ plotly_build.plotly_hash <- function(l = last_plot()) {
340340
points_df <- data.frame(dat_index = seq_along(dat[["x"]] %||% dat[["y"]] %||% dat[["z"]])) %>% # indices of the original data elements used in the trace FIXME properly define data length
341341
tracify_by_color(dat) %>%
342342
tracify_by_column(dat, "symbol", force_numeric=TRUE) %>%
343-
tracify_by_column(dat, "group", force_numeric=TRUE)
343+
tracify_by_column(dat, "group", force_numeric=TRUE) %>%
344+
tracify_by_column(dat, "legenditem", force_numeric=TRUE)
344345
subtrace_key_cols <- setdiff(colnames(points_df), "dat_index")
345346
trace_key_cols <- setdiff(subtrace_key_cols, "group_index")
346347
points_df <- dplyr::arrange_(points_df, .dots = c(subtrace_key_cols, "dat_index")) %>%
@@ -398,6 +399,17 @@ plotly_build.plotly_hash <- function(l = last_plot()) {
398399
if (!is.null(dat[["symbol"]])) {
399400
trace_brushes <- append(trace_brushes, symbol_brush(dat))
400401
}
402+
if ("legenditem_index" %in% trace_key_cols) {
403+
legenditems <- unique(dat[["legenditem"]])
404+
first_traces <- dplyr::group_by(points_df, legenditem_index) %>% dplyr::filter(row_number() == 1) %>% .$trace_index
405+
trace_brushes <- append(trace_brushes, function(trace, trace_ix, dat, dat_indices) {
406+
trace$legendgroup <- trace[["legenditem"]][[1]]
407+
trace$name <- trace[["legenditem"]][[1]] # override the trace name by legenditem
408+
trace$showlegend <- trace_ix %in% first_traces # put each trace group to legend once
409+
trace$legenditem <- NULL
410+
trace
411+
})
412+
}
401413
generate_traces(dat, max(points_df$dat_index, na.rm=TRUE), trace_dat_indices, trace_brushes)
402414
} else {
403415
list(d)

0 commit comments

Comments
 (0)