Skip to content

Instantly share code, notes, and snippets.

@jbothma
Created July 10, 2023 07:48
Show Gist options
  • Save jbothma/7268e50ce1cfaf5a497c56c78e5928f7 to your computer and use it in GitHub Desktop.
Save jbothma/7268e50ce1cfaf5a497c56c78e5928f7 to your computer and use it in GitHub Desktop.
grouped horizonal bar chart
{
"$schema": "https://vega.github.io/schema/vega/v5.json",
"description": "A basic grouped bar chart example.",
"width": 300,
"height": 240,
"padding": 5,
"data": [
{
"name": "table",
"values": [
{"category": "School/post-school", "year": 2011, "value": 28},
{"category": "School/post-school", "year": 2016, "value": 27},
{"category": "School/post-school", "year": 2021, "value": 25},
{"category": "NEET", "year": 2011, "value": 38},
{"category": "NEET", "year": 2016, "value": 40},
{"category": "NEET", "year": 2021, "value": 41},
{"category": "Employed", "year": 2011, "value": 33},
{"category": "Employed", "year": 2016, "value": 32},
{"category": "Employed", "year": 2021, "value": 33}
]
}
],
"scales": [
{
"name": "yscale",
"type": "band",
"domain": {"data": "table", "field": "category"},
"range": "height",
"padding": 0.2
},
{
"name": "xscale",
"type": "linear",
"domain": {"data": "table", "field": "value"},
"range": "width",
"round": true,
"zero": true,
"nice": true
},
{
"name": "color",
"type": "ordinal",
"domain": {"data": "table", "field": "year"},
"range": {"scheme": "category20"}
}
],
"axes": [
{
"orient": "left",
"scale": "yscale",
"tickSize": 0,
"labelPadding": 4,
"zindex": 1
},
{"orient": "bottom", "scale": "xscale"}
],
"marks": [
{
"type": "group",
"from": {
"facet": {"data": "table", "name": "facet", "groupby": "category"}
},
"encode": {"enter": {"y": {"scale": "yscale", "field": "category"}}},
"signals": [{"name": "height", "update": "bandwidth('yscale')"}],
"scales": [
{
"name": "pos",
"type": "band",
"range": "height",
"domain": {"data": "facet", "field": "year"}
}
],
"marks": [
{
"name": "bars",
"from": {"data": "facet"},
"type": "rect",
"encode": {
"enter": {
"y": {"scale": "pos", "field": "year"},
"height": {"scale": "pos", "band": 1},
"x": {"scale": "xscale", "field": "value"},
"x2": {"scale": "xscale", "value": 0},
"fill": {"scale": "color", "field": "year"}
}
}
},
{
"type": "text",
"from": {"data": "bars"},
"encode": {
"enter": {
"x": {"field": "x2", "offset": -5},
"y": {"field": "y", "offset": {"field": "height", "mult": 0.5}},
"fill": [
{
"test": "contrast('white', datum.fill) > contrast('black', datum.fill)",
"value": "white"
},
{"value": "black"}
],
"align": {"value": "right"},
"baseline": {"value": "middle"},
"text": {"field": "datum.value"}
}
}
}
]
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment