Vega-Lite:分面图表旁加表格,hconcat应如何放置?
解决Vega-Lite横向拼接Likert分面图表与统计表格的问题
直接通过hconcat将Likert图表和统计表格的配置对象放在同一数组中即可实现横向并排,以下是具体实现步骤和示例:
核心思路
- 将你的分面Likert图表配置与统计表格配置作为独立的Vega-Lite spec,放入
hconcat数组内 - 统计表格直接使用你提前聚合好的均值、中位数等数据,无需实时计算
- 调整两个组件的宽度比例,保证布局协调
代码示例
假设你已有:
- 原始Likert数据(
likert_data) - 提前聚合的统计数据(
stats_data,结构为每个问题一行,包含question_section、question_text、mean、median等字段)
完整配置如下:
{ "$schema": "https://vega.github.io/schema/vega-lite/v5.json", "hconcat": [ // 左侧分面Likert图表 { "data": {"name": "likert_data"}, "width": 600, "facet": { "row": {"field": "question_section", "title": "问题板块"}, "column": {"field": "question_text", "title": "问题文本"} }, "mark": "bar", "encoding": { "x": { "field": "count", "type": "quantitative", "title": "占比", "stack": "normalize" }, "y": {"field": "response", "type": "ordinal", "title": "反馈等级"}, "color": {"field": "response", "type": "nominal"} } }, // 右侧统计表格 { "data": {"name": "stats_data"}, "width": 250, "mark": {"type": "text", "align": "center", "baseline": "middle"}, "encoding": { "x": { "field": "stat_type", "type": "nominal", "axis": {"title": "统计指标", "labelAngle": 0} }, "y": { "field": "question_text", "type": "nominal", "axis": {"title": null} }, "text": {"field": "value", "type": "quantitative", "format": ".2f"}, "row": {"field": "question_section", "title": null} }, "transform": [ // 将宽表结构的统计数据转为长表,适配表格展示 {"fold": ["mean", "median"], "as": ["stat_type", "value"]} ] } ] }
关键细节说明
- 宽度控制:给两个子组件分别设置
width,根据需求调整比例(比如图表占70%、表格占30%) - 表格数据处理:如果你的统计数据是宽表(每个问题一行,统计指标为列),用
fold转换成长表结构,方便用x轴映射统计类型、y轴映射问题文本 - 分面对齐:表格和图表使用相同的
question_section字段做行分面,保证视觉上的板块对齐 - 表格样式优化:通过
mark的align和baseline属性让文本居中,提升表格可读性
内容的提问来源于stack exchange,提问作者cwollett
相关产品推荐
相关产品推荐

