如何用Power BI Deneb可视化工具通过Vega Lite展示双折线图
在Power BI Deneb(Vega-Lite)中展示双年份请假次数折线图
一、先调整数据格式(关键前提)
如果你的数据是宽格式(即每列对应一个年份的请假次数,比如MONTH、Leaves Count 2022、Leaves Count 2023),需要转成长格式:
- 打开Power Query编辑器,选中
Leaves Count 2022和Leaves Count 2023两列 - 点击「转换」选项卡 → 「逆透视列」→ 「逆透视所选列」
- 重命名生成的列:将「属性」改为
Year,「值」改为Leaves Count - 加载数据回Power BI
二、修改后的Vega-Lite代码
{ "data": {"name": "dataset"}, "layer": [ // 区域填充层(双年份) { "mark": { "type": "area", "line": {"color": {"expr": "datum.Year == '2022' ? '#636efa' : '#7b516f'"}}, "color": { "x1": 1, "y1": 1, "gradient": "linear", "stops": [ {"offset": 0, "color": "white"}, {"offset": 0.8, "color": {"expr": "datum.Year == '2022' ? '#636efa' : '#7b516f'"}} ] }, "opacity": 0.6 }, "encoding": { "color": {"field": "Year", "type": "nominal", "legend": {"title": "年份"}} } }, // 折线/竖线层(双年份) { "mark": { "type": "bar", "width": 2, "clip": true }, "encoding": { "opacity": { "condition": {"test": {"field": "__selected__", "equal": "off"}, "value": 0.1}, "value": 1 }, "color": {"field": "Year", "type": "nominal"}, "y": {"field": "__highlight_Leaves Count", "type": "quantitative", "axis": null} } }, // 非选中状态的数值文本 { "mark": { "type": "text", "yOffset": -10, "size": 10, "opacity": 0.2 }, "encoding": { "text": {"field": "Leaves Count"}, "color": {"field": "Year", "type": "nominal"} } }, // 选中状态的数值文本 { "mark": { "type": "text", "yOffset": -10, "size": 10 }, "encoding": { "text": {"field": "Leaves Count"}, "opacity": { "condition": {"test": {"field": "__selected__", "equal": "off"}, "value": 0.1}, "value": 1 }, "color": {"field": "Year", "type": "nominal"}, "y": {"field": "__highlight_Leaves Count", "type": "quantitative", "axis": null} } } ], "encoding": { "x": { "field": "MONTH", "type": "ordinal", "axis": {"labelPadding": 0}, "title": null }, "y": { "field": "Leaves Count", "type": "quantitative", "axis": {"title": "请假次数"} } } }
三、关键调整说明
- 数据适配:代码基于长格式数据编写,通过
Year字段区分两个年份的系列,用color编码自动生成不同颜色的折线/区域 - 高亮字段适配:将原来的
__1____highlight替换为__highlight_Leaves Count(Deneb中高亮字段命名规则为__highlight_[度量值名称]) - 颜色区分:通过表达式
datum.Year == '2022' ? '#636efa' : '#7b516f'给两个年份设置不同的主题色,可自行修改颜色值 - 图例添加:在
color编码中添加了legend配置,方便区分两个年份的系列
替代方案(无需改数据格式)
如果不想调整数据格式,也可以通过多Layer分别定义每个年份的方式实现:
{ "data": {"name": "dataset"}, "layer": [ // 2022年系列 { "mark": {"type": "area", "line": {"color": "#636efa"}, "opacity": 0.6}, "encoding": { "y": {"field": "Leaves Count 2022", "type": "quantitative"} } }, // 2023年系列 { "mark": {"type": "area", "line": {"color": "#7b516f"}, "opacity": 0.6}, "encoding": { "y": {"field": "Leaves Count 2023", "type": "quantitative"} } } // 其他bar、text层可按此逻辑复制,分别对应两个年份的字段 ], "encoding": { "x": { "field": "MONTH", "type": "ordinal", "axis": {"labelPadding": 0}, "title": null } } }
注:这种方式需要复制所有图层元素分别对应两个年份的字段,灵活性不如长格式。
内容的提问来源于stack exchange,提问作者userrr
相关产品推荐
相关产品推荐

