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

Vega Lite散点图中Regression Line无法显示问题求助

散点图添加Regression转换后回归线无法显示的问题解决

我尝试为散点图添加Regression转换,但可视化界面中无法显示回归线,配置代码如下:

"layer": [
  {
    "mark": {"type":"circle","color":"rgb(0,47,167)","size":60},
    "encoding": { 
      "x": { "field": "supply", "type": "quantitative","title":null },
      "y": { "field": "price", "type": "quantitative","title":null }
    }
  },
  {  
    "mark": {"type": "line", "color": "firebrick"},
    "transform": [
      {"regression": "price", "on": "supply"}
    ],
    "encoding": {
      "x": {"field": "supply", "type": "quantitative"},
      "y": {"field": "price", "type": "quantitative"}
    }
  },
  {  
    "transform": [
      {
        "regression": "price",
        "on": "supply",
        "params": true
      },
      {"calculate": "'R²: '+format(datum.rSquared, '.2f')", "as": "R2"}
    ],
    "mark": {
      "type": "text",
      "color": "firebrick",
      "x": "width",
      "align": "right",
      "y": -5
    },
    "encoding": {"text": {"type": "nominal", "field": "R2"}}
  }
]

问题原因

回归线图层的encoding中,y字段绑定了原始的price字段,但Regression转换默认会将回归预测值输出到regression字段,而非保留原始price数据。这就导致线条没有对应的数据可以渲染,所以无法显示。

修正方案

将回归线图层的y字段改为绑定回归转换生成的regression字段,修改后的代码如下:

"layer": [
  {
    "mark": {"type":"circle","color":"rgb(0,47,167)","size":60},
    "encoding": { 
      "x": { "field": "supply", "type": "quantitative","title":null },
      "y": { "field": "price", "type": "quantitative","title":null }
    }
  },
  {  
    "mark": {"type": "line", "color": "firebrick"},
    "transform": [
      {"regression": "price", "on": "supply"}
    ],
    "encoding": {
      "x": {"field": "supply", "type": "quantitative"},
      // 绑定回归转换生成的预测值字段
      "y": {"field": "regression", "type": "quantitative"}
    }
  },
  {  
    "transform": [
      {
        "regression": "price",
        "on": "supply",
        "params": true
      },
      {"calculate": "'R²: '+format(datum.rSquared, '.2f')", "as": "R2"}
    ],
    "mark": {
      "type": "text",
      "color": "firebrick",
      "x": "width",
      "align": "right",
      "y": -5
    },
    "encoding": {"text": {"type": "nominal", "field": "R2"}}
  }
]

如果需要自定义预测值字段名,可以在regression转换中添加as参数指定,比如:

"transform": [
  {"regression": "price", "on": "supply", "as": "predicted_price"}
]

此时y字段对应改为"field": "predicted_price"即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 23:15:27