在Plotly中映射color时如何向customdata传入多列数据?
解决Plotly映射color后customdata列尺寸不兼容的错误
当未对color映射分组变量时,以下代码可正常运行:
library(tidyverse) library(plotly) set.seed(123) d <- tibble(x = 1:10, g = gl(2, 5), y = sample(100, 10), L = LETTERS[1:10], l = letters[1:10]) plot_ly(d) %>% add_bars(x = ~ x, y = ~ y, customdata = ~ map2(l, L, list), hovertemplate = "%{customdata[0]}:%{customdata[1]}")
但添加color=~g映射分组颜色后,会触发如下错误:
Error in `recycle_columns()`: ! Tibble columns must have compatible sizes. • Size 5: Columns `x`, `y`, `color`, `hovertemplate`, `.plotlyTraceIndex`, and 2 more. • Size 10: Column `customdata`. ℹ Only values of size one are recycled. Run `rlang::last_trace()` to see where the error occurred.
原因分析
使用color=~g时,Plotly会自动按g的水平将原始数据拆分为多个独立trace(此处g有2个水平,对应2个trace,每个trace含5行数据)。原代码中map2(l, L, list)生成的是长度为10的列表,无法与每个trace的5行数据尺寸匹配,导致列兼容报错。
解决方案
将customdata转换为矩阵格式,让Plotly能按分组正确拆分数据,保证每个trace的customdata尺寸与x、y一致。修改后的代码如下:
library(tidyverse) library(plotly) set.seed(123) d <- tibble(x = 1:10, g = gl(2, 5), y = sample(100, 10), L = LETTERS[1:10], l = letters[1:10]) plot_ly(d) %>% add_bars(x = ~ x, y = ~ y, color = ~g, # 将l和L合并为矩阵,替代原列表格式 customdata = ~cbind(l, L), hovertemplate = "%{customdata[0]}:%{customdata[1]}")
原理说明
cbind(l, L)生成10行2列的矩阵,Plotly按g分组时,会将矩阵拆分为两个5行2列的子矩阵,分别对应每个trace的customdata,此时customdata的尺寸(5行)与x、y的尺寸完全匹配,解决了列兼容问题。也可以用data.frame(l, L)替代cbind(l, L),效果一致。
内容的提问来源于stack exchange,提问作者thothal
相关产品推荐
相关产品推荐

