简体   繁体   中英

Vega-lite: Change order of stacks in a stacked bar chart and ignore negative value

This is the chart I am trying to follow for my work

Vega editor

在此处输入图像描述

How could I change the order of the 'Measure' to keep 'Measure 1' at the top only by ignoring that it is a negative value? I still want to show the '-' sign in the text but I want the bar to go to the top.

For David: One of the bars are in such a way where the top blue bar can be negative but should always be on the top

: 在此处输入图像描述

Like this? If so, you need a sort.

在此处输入图像描述

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "data": {
    "values": [
      {"Value": 0.321, "Date": "09/30/2021", "Measure": "Measure 4"},
      {"Value": 0.031, "Date": "09/30/2021", "Measure": "Measure 3"},
      {"Value": 0.123, "Date": "09/30/2021", "Measure": "Measure 2"},
      {"Value": -0.475, "Date": "09/30/2021", "Measure": "Measure 1"}
    ]
  },
  "width": 500,
  "height": 250,
  "resolve": {"scale": {"color": "independent"}},
  "layer": [
    {
      "mark": "bar",
      "encoding": {
        "y": {
          "field": "Value",
          "type": "quantitative",
          "axis": {"format": ".1%"},
          "sort": "descending"
        },
        "x": {"field": "Date", "type": "nominal", "axis": {"labelAngle": -45}},
        "color": {"field": "Measure", "type": "nominal"}
      }
    },
    {
      "transform": [
        {
          "stack": "Value",
          "groupby": ["Date"],
          "as": ["lower", "upper"],
          "sort": [{"field": "Measure", "order": "descending"}]
        },
        {"calculate": "(datum.lower + datum.upper) / 2", "as": "midpoint"}
      ],
      "mark": {"type": "text"},
      "encoding": {
        "y": {"field": "midpoint", "type": "quantitative"},
        "x": {"field": "Date", "type": "nominal"},
        "color": {
          "field": "Measure",
          "type": "nominal",
          "scale": {"range": ["white"]},
          "legend": null
        },
        "text": {"aggregate": "sum", "field": "Value"}
      }
    }
  ]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM