Skip to content

Commit 14c99fd

Browse files
committed
add "legenditem" property
legenditem allows to group multiply traces into one legend item
1 parent cef36dd commit 14c99fd

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
@@ -335,7 +335,8 @@ plotly_build.plotly_hash <- function(l = last_plot()) {
335335
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
336336
tracify_by_color(dat) %>%
337337
tracify_by_column(dat, "symbol", force_numeric=TRUE) %>%
338-
tracify_by_column(dat, "group", force_numeric=TRUE)
338+
tracify_by_column(dat, "group", force_numeric=TRUE) %>%
339+
tracify_by_column(dat, "legenditem", force_numeric=TRUE)
339340
subtrace_key_cols <- setdiff(colnames(points_df), "dat_index")
340341
trace_key_cols <- setdiff(subtrace_key_cols, "group_index")
341342
points_df <- dplyr::arrange_(points_df, .dots = c(subtrace_key_cols, "dat_index")) %>%
@@ -393,6 +394,17 @@ plotly_build.plotly_hash <- function(l = last_plot()) {
393394
if (!is.null(dat[["symbol"]])) {
394395
trace_brushes <- append(trace_brushes, symbol_brush(dat))
395396
}
397+
if ("legenditem_index" %in% trace_key_cols) {
398+
legenditems <- unique(dat[["legenditem"]])
399+
first_traces <- dplyr::group_by(points_df, legenditem_index) %>% dplyr::filter(row_number() == 1) %>% .$trace_index
400+
trace_brushes <- append(trace_brushes, function(trace, trace_ix, dat, dat_indices) {
401+
trace$legendgroup <- trace[["legenditem"]][[1]]
402+
trace$name <- trace[["legenditem"]][[1]] # override the trace name by legenditem
403+
trace$showlegend <- trace_ix %in% first_traces # put each trace group to legend once
404+
trace$legenditem <- NULL
405+
trace
406+
})
407+
}
396408
generate_traces(dat, max(points_df$dat_index, na.rm=TRUE), trace_dat_indices, trace_brushes)
397409
} else {
398410
list(d)

0 commit comments

Comments
 (0)