对条形图的堆栈段进行排序

时间:2020-05-07 09:18:48

标签: vega-lite

我玩过堆积的条形图,并想用Vega Lite创建西班牙国旗。 我在数据中指定了条纹的高度和颜色,但没有对单个堆栈进行排序:

Spanish Flag wrongly ordered

我将比例尺设置为null,以便从指定的字段获取颜色。 我在pos属性中对条带的位置进行了编码,并希望按此对片段进行排序。 我还尝试稍微改变红色条纹的颜色,但这没有帮助。

规格:

{
  "$schema": "https://vega.github.io/schema/vega-lite/v4.json",
  "description": "Fun with Flags",
  "data": {
    "values": [
      {"h": 5, "color": "#aa151b", "pos": 6, "country": "spain"},
      {"h": 5, "color": "#f1bf00", "pos": 4, "country": "spain"},
      {"h": 5, "color": "#aa152b", "pos": 2, "country": "spain"}
    ]
  },
  "width": {"step": 300},
  "mark": {"type": "bar"},
  "encoding": {
    "x": {"field": "country", "type": "nominal"},
    "y": {"field": "h", "type": "quantitative"},
    "color": { 
      "field": "color", 
      "scale": null,
      "type": "nominal",
      "sort": {"field": "pos", "op": "min", "order": "descending"}
    }
  }
}

这里是Vega Editor with the Spec的链接。

1 个答案:

答案 0 :(得分:0)

除了对颜色编码进行排序外,我还必须将订单渠道指定为described in the docs

这给了我以下规格:

{
  "$schema": "https://vega.github.io/schema/vega-lite/v4.json",
  "description": "Fun with Flags",
  "data": {
    "values": [
      {"h": 5, "color": "#aa152b", "pos": 6, "country": "spain"},
      {"h": 5, "color": "#f1bf00", "pos": 4, "country": "spain"},
      {"h": 5, "color": "#aa152b", "pos": 2, "country": "spain"}
    ]
  },
  "width": {"step": 300},
  "mark": {"type": "bar"},
  "encoding": {
    "x": {"field": "country", "type": "nominal"},
    "y": {"field": "h", "type": "quantitative"},
    "color": { 
      "field": "color", 
      "scale": null,
      "type": "nominal"
    },
    "order": {
      "field": "pos",
      "type": "quantitative"
    }
  }
}

正确的西班牙国旗:

enter image description here

Link to Vega Editor