Vega Lite - 条形图 - 排序不正确

Vega Lite - Bar Chart - Incorrectly Sorted

我刚刚在 Vega Lite 中制作了一个简单的条形图,在这里效果很好:

{
    "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
    "width": 800,
    "height": 600,
    "title": "Biggest Killers",
    "data": {"url": "https://raw.githubusercontent.com/githubuser0099/Assignment2.1/main/Cause_Of_Death_v2.csv"},
    "mark": "bar",
    "encoding": {
        "x": {"field": "Toll", "type": "quantitative", "title": ""},
        "y": {"field": "Cause Of Death", "type": "nominal", "title": "", "sort": "-x"}
        }
}

但是,当我尝试添加配色方案时,最长的条形为最深的红色,最短的条形为最浅的红色,出于某种原因部分我的排序中断:

{
    "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
    "width": 800,
    "height": 600,
    "title": "Biggest Killers",
    "data": {"url": "https://raw.githubusercontent.com/githubuser0099/Assignment2.1/main/Cause_Of_Death_v2.csv"},
    "mark": "bar",
    "encoding": {
        "x": {"field": "Toll", "type": "quantitative", "title": ""},
        "y": {"field": "Cause Of Death", "type": "nominal", "title": "", "sort": "-x"},
        "color": {
            "field": "Toll", 
            "type": "quantitative", 
            "scale": {"scheme": "reds"}
        }
    }
}

有什么想法吗?任何帮助将不胜感激。

您的排序变得混乱的原因可能是因为您的 Toll 字段的值是字符串,所以您只需将该字段转换为数字,如下所示:

"transform": [{"calculate": "toNumber(datum.Toll)", "as": "Toll"}],

或提供 y-axis 作为降序排序,似乎也有效:

"y": {
      "field": "Cause Of Death",
      "type": "nominal",
      "title": "",
      "sort": {"order": "descending"}
    },

下面是方法 1 和 2 的代码片段:

方法一:

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "width": 800,
  "height": 600,
  "title": "Biggest Killers",
  "data": {
    "url": "https://raw.githubusercontent.com/githubuser0099/Assignment2.1/main/Cause_Of_Death_v2.csv"
  },
  "mark": "bar",
  "transform": [{"calculate": "toNumber(datum.Toll)", "as": "Toll"}],
  "encoding": {
    "x": {"field": "Toll", "type": "quantitative", "title": ""},
    "y": {
      "field": "Cause Of Death",
      "type": "nominal",
      "title": "",
      "sort": "-x"
    },
    "color": {
      "field": "Toll",
      "type": "quantitative",
      "scale": {"scheme": "reds"}
    }
  }
}

方法二:

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "width": 800,
  "height": 600,
  "title": "Biggest Killers",
  "data": {
    "url": "https://raw.githubusercontent.com/githubuser0099/Assignment2.1/main/Cause_Of_Death_v2.csv"
  },
  "mark": "bar",
  "encoding": {
    "x": {"field": "Toll", "type": "quantitative", "title": ""},
    "y": {
      "field": "Cause Of Death",
      "type": "nominal",
      "title": "",
      "sort": {"order": "descending"}
    },
    "color": {
      "field": "Toll",
      "type": "quantitative",
      "scale": {"scheme": "reds"}
    }
  }
}