如何控制 vega-lite 堆叠条形图中组的顺序

how to control the order of groups in a vega-lite stacked bar chart

给定一个堆积条形图,如本例所示:https://vega.github.io/editor/?#/examples/vega-lite/stacked_bar_weather

我想控制聚合中项目的顺序,例如,'fog' 排在底部,接下来是 'sun' 等等。这可能吗?

这是因为我有一种比其他的大很多。我希望它出现在底部,然后将域控制到该部分的大部分 'cut off'。

谢谢

您可以通过 order 编码控制堆栈顺序:参见 https://vega.github.io/vega-lite/docs/stack.html#sorting-stack-order

不幸的是,这只允许按字段值排序,而不是像您在这里想要的那样按显式顺序排序。解决方法是使用 calculate transform to turn your explicit order into a field (view in editor):

{
  "$schema": "https://vega.github.io/schema/vega-lite/v4.json",
  "data": {"url": "data/seattle-weather.csv"},
  "transform": [
    {
      "calculate": "indexof(['sun', 'fog', 'drizzle', 'rain', 'snow'], datum.weather)",
      "as": "order"
    }
  ],
  "mark": "bar",
  "encoding": {
    "x": {
      "timeUnit": "month",
      "field": "date",
      "type": "ordinal",
      "axis": {"title": "Month of the year"}
    },
    "y": {"aggregate": "count", "type": "quantitative"},
    "color": {
      "field": "weather",
      "type": "nominal",
      "scale": {
        "domain": ["sun", "fog", "drizzle", "rain", "snow"],
        "range": ["#e7ba52", "#c7c7c7", "#aec7e8", "#1f77b4", "#9467bd"]
      },
      "legend": {"title": "Weather type"}
    },
    "order": {"field": "order", "type": "ordinal"}
  }
}