如何用echarts4r创建带双层分组X轴的数据透视图表?
双层分组X轴数据透视图表的echarts4r实现方案
需求说明
需要使用echarts4r复刻带有双层分组X轴的数据透视图表,X轴包含两级分组标签(market为一级,group为二级)。已有ECharts原生实现方案,需转换为echarts4r代码。
测试数据
dd <- data.frame( market = rep(c("Left", "Right"), each = 6), gender = rep(rep(c("Female", "Male"), each = 3), 2), group = c("Top", "Middle", "Bottom"), value = c(10, 2, 4, 5, 1, 7, 7, 4, 1, 2, 5, 6) ) library(echarts4r) library(htmlwidgets) # 用于嵌入JS函数
ECharts原生参考配置
option = { tooltip: { trigger: 'axis', axisPointer: { type: 'cross', crossStyle: { color: '#999' } } }, toolbox: { feature: { magicType: { show: true, type: ['line', 'bar'] }, restore: { show: true }, saveAsImage: { show: true } } }, legend: { data: ['Female', 'Male'] }, xAxis: [ { type: 'category', data: ["Bottom", "Middle", "Top", "Bottom", "Middle", "Top"], axisPointer: { type: 'shadow' } }, { type: "category", axisTick: { show: true, alignWithLabel: false, length: 40, align: "left", interval: function(index, value) { return value ? true : false; }}, offset: -700, axisLine: { show: false }, data: ["Left", "Right"] } ], yAxis: [ { type: 'value', name: 'Value', min: 0, max: 12, interval: 2, axisLabel: { formatter: function(value) { return value; } } } ], series: [ { name: 'Male', type: 'bar', tooltip: { valueFormatter: function (value) { return value; } }, data: [ 7, 1, 5, 6, 5, 2 ] }, { name: 'Female', type: 'bar', tooltip: { valueFormatter: function (value) { return value; } }, data: [ 4, 2, 10, 1, 4, 7 ] } ] };
echarts4r实现代码
# 确保数据顺序与X轴标签对应 dd_sorted <- dd |> arrange(market, gender, group) |> mutate(x_label = rep(c("Bottom", "Middle", "Top"), 2)) # 对应第一级X轴标签 dd_sorted |> group_by(gender) |> e_charts() |> # 第一级X轴(group标签) e_x_axis( type = "category", data = unique(dd_sorted$x_label), axisPointer = list(type = "shadow") ) |> # 第二级X轴(market标签) e_x_axis( type = "category", data = c("Left", "Right"), axisTick = list( show = TRUE, alignWithLabel = FALSE, length = 40, align = "left", interval = JS("function(index, value) { return value ? true : false; }") ), offset = -700, axisLine = list(show = FALSE) ) |> # Y轴配置 e_y_axis( type = "value", name = "Value", min = 0, max = 12, interval = 2 ) |> # 柱状图系列,指定对应第一级X轴 e_bar(value, x_index = 0) |> # 提示框配置 e_tooltip( trigger = "axis", axisPointer = list( type = "cross", crossStyle = list(color = "#999") ) ) |> # 工具箱配置 e_toolbox( feature = list( magicType = list(show = TRUE, type = c("line", "bar")), restore = list(show = TRUE), saveAsImage = list(show = TRUE) ) ) |> # 图例 e_legend()
关键说明
- 数据排序:必须确保数据顺序与X轴标签的顺序完全对应,否则柱状图会错位;
- 多X轴指定:通过
x_index = 0指定柱状图系列绑定到第一级X轴; - JS函数嵌入:使用
htmlwidgets::JS()将原生ECharts中的JS回调函数(如interval逻辑)嵌入到echarts4r配置中; - 轴样式调整:第二级X轴通过
offset调整位置,隐藏轴线并自定义刻度样式,实现分组标签的层级效果。
内容的提问来源于stack exchange,提问作者David
相关产品推荐
相关产品推荐

