kristoff
kristoff

Reputation: 103

How to create Grouped Bar Chart in Vegalite?

Name | Value 1 | Value 2
BTC  | 1       | 2
ETH  | 1       | 2

to this:

Tried to used this as an example: https://vega.github.io/vega-lite/examples/bar_grouped.html, but I can't make it work.

Can someone please point me to the right direction? Thank you in advance.

Upvotes: 2

Views: 1768

Answers (1)

wahab memon
wahab memon

Reputation: 2416

Instead of using column provided in your question, You can simply use layers and keep the x axis as common and provide value1 and value2 in y axis of each layer respectively and simply provide some offset to show it as a grouped bar chart. Below is the basic spec configuration and editor:

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "description": "A simple bar chart with embedded data.",
  "title": "My chart",
  "width": 200,
  "data": {
    "values": [
      {"name": "BTH", "value1": 28, "value2": 24, "legendTitle": "value1"},
      {"name": "ETH", "value1": 55, "value2": 25, "legendTitle": "value2"}
    ]
  },
  "encoding": {
    "x": {"field": "name", "type": "nominal", "axis": {"labelAngle": 0}}
  },
  "layer": [
    {
      "mark": {"type": "bar", "xOffset": -20, "size": 30, "color": "skyblue"},
      "encoding": {
        "y": {
          "field": "value1",
          "type": "quantitative",
          "axis": {"title": null, "ticks": false}
        }
      }
    },
    {
      "mark": {"type": "bar", "size": 30, "xOffset": 18, "color": "orange"},
      "encoding": {
        "y": {
          "field": "value2",
          "type": "quantitative",
          "axis": {"title": null, "ticks": false}
        }
      }
    },
    {
      "mark": {"type": "text"},
      "encoding": {
        "fill": {
          "field": "legendTitle",
          "scale": {"range": ["skyBlue", "orange"]},
          "legend": {"title": null, "symbolType": "square", "orient": "bottom"}
        }
      }
    }
  ]
}

Upvotes: 2

Related Questions