You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vega-Lite中分箱数据直方图叠加密度线及x轴标签配置问题

问题1:直方图叠加密度分布线

可以实现,需要将原来的单mark配置改为layer图层结构,第一层保留原有直方图配置,第二层新增密度线配置。由于你使用的是预分箱的聚合数据,密度线可以直接基于已有分箱起始值和count值绘制,也可以通过density变换生成拟合后的平滑密度曲线,需要注意指定count字段为权重值。

问题2:X轴显示全部刻度并支持倾斜

只需在X轴的encoding配置中新增axis属性即可:

  • 设置labelAngle: -45可让刻度标签45度倾斜
  • 设置tickMinStep: 2和你的分箱步长保持一致,即可展示所有分箱对应的刻度值
  • 新增labelOverlap: false避免标签重叠隐藏

修改后完整配置代码

{
  "$schema": "https://vega.github.io/schema/vega-lite/v2.6.json",
  "data": {
    "url" : {
        "index": "artefact_data",
        "body": {
          "size":10000,
          "_source": ["bin_start", "bin_end", "count"]        
        }
      },
      "format": {"property": "hits.hits"}
  },
  "layer": [
    // 第一层:原有直方图
    {
      "mark": "bar",
      "encoding": {
        "x": {
          "field": "_source.bin_start",
          "bin": {"binned": true, "step": 2},
          "axis": {
            "labelAngle": -45,
            "tickMinStep": 2,
            "labelOverlap": false
          }
        },
        "x2": {"field": "_source.bin_end"},
        "y": {
          "field": "_source.count",
          "type": "quantitative"    
        },
        "color": {"value": "green"},
        "opacity": {"value": 0.6},
        "tooltip": [
          {"field": "_source.count", "type": "quantitative", "title":"Count"}
        ]
      }
    },
    // 第二层:密度分布线
    {
      "mark": {"type": "line", "color": "red", "strokeWidth": 2},
      "transform": [
        {
          "density": "_source.bin_start",
          "weight": "_source.count",
          "bandwidth": 2
        }
      ],
      "encoding": {
        "x": {"field": "value", "type": "quantitative"},
        "y": {"field": "density", "type": "quantitative", "axis": null}
      }
    }
  ]
}

如果不需要平滑拟合的密度曲线,只需要直接连接每个分箱顶部的折线,可以把第二层的transform去掉,直接配置x为_source.bin_start,y为_source.count即可。


内容的提问来源于stack exchange,提问作者hanzgs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 06:45:03