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

如何在已排序的Vega-Lite图表中仅显示前十条结果

Vega-Lite 图表:排序后仅显示前十条并指定特定项末尾展示

需求概述

  • 已完成图表基础排序,需实现仅展示前十条结果
  • 要求将George作为前十条中最后一个展示的代理

未排名图表示例

未排名图表:图表描述/图片占位

原Vega-Lite配置代码

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "data": {"url": "your-data-source"},
  "mark": "bar",
  "encoding": {
    "x": {"field": "agent", "type": "nominal"},
    "y": {"field": "value", "type": "quantitative"},
    "order": {"field": "value", "type": "quantitative", "sort": "descending"}
  }
}

实现方案

1. Elixir数据预处理代码

先对数据按原有规则排序,提取前9条非George的记录,再将George追加到末尾(若存在),确保总条数为10:

defmodule ChartDataProcessor do
  def get_top_ten_with_george_last(raw_data) do
    # 按原有排序规则(比如value降序)排序数据
    sorted = Enum.sort_by(raw_data, & &1.value, :desc)
    
    # 分离George和其他数据
    {george, others} = Enum.split_with(sorted, &(&1.agent == "George"))
    
    # 取前9条非George数据,加上George(如果存在)
    top_nine = Enum.take(others, 9)
    if Enum.empty?(george) do
      Enum.take(sorted, 10)
    else
      top_nine ++ george
    end
  end
end

2. 更新Vega-Lite配置

将预处理后的数据集传入图表,关闭x轴自动排序,直接使用数据的现有顺序:

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "data": {"values": "预处理后的数据集"}, // 替换为Elixir输出的处理后数据
  "mark": "bar",
  "encoding": {
    "x": {"field": "agent", "type": "nominal", "sort": null}, // 禁用自动排序,使用数据原生顺序
    "y": {"field": "value", "type": "quantitative"}
  }
}

核心逻辑说明

  • 数据层面通过Elixir完成筛选和位置调整,确保George在前十的最后一位
  • Vega-Lite配置中依赖预处理后的数据顺序,避免图表自动排序破坏自定义规则

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 09:48:09