Skip to content

Instantly share code, notes, and snippets.

@PBI-DataVizzle
Last active December 22, 2023 08:29
Show Gist options
  • Save PBI-DataVizzle/d0d1e2abbbf25bb16f6e80420155f381 to your computer and use it in GitHub Desktop.
Save PBI-DataVizzle/d0d1e2abbbf25bb16f6e80420155f381 to your computer and use it in GitHub Desktop.
bar_with_labels_and_CF
{
"$schema": "https://vega.github.io/schema/vega-lite/v5.json",
"description": "A simple bar chart with conditional coloring for the highest and lowest values and data labels.",
"data": {
"values": [
{"a": "A", "b": 2800},
{"a": "B", "b": 5500},
{"a": "C", "b": 4300},
{"a": "G", "b": 1900},
{"a": "H", "b": 8700},
{"a": "I", "b": 5200},
{"a": "D", "b": 9100},
{"a": "E", "b": 8100},
{"a": "F", "b": 5300}
]
},
"transform": [
{
"window": [
{"op": "max", "field": "b", "as": "max_b"},
{"op": "min", "field": "b", "as": "min_b"}
],
"frame": [null, null]
}
],
"layer": [
{
"mark": "bar",
"encoding": {
"x": {
"field": "a",
"type": "nominal",
"axis": {
"title": "Category",
"labelAlign": "center", // Adjust the label alignment as needed
"labelAngle": 0 // Set the angle of the labels
}
},
"y": {
"field": "b",
"type": "quantitative",
"axis": {
"title": "Value",
"labelPadding": 5 // Adjust padding to position labels closer or further from the axis
}
},
"color": {
"condition": [
{
"test": "datum.b === datum.max_b",
"value": "green" // Color for the highest value
},
{
"test": "datum.b === datum.min_b",
"value": "red" // Color for the lowest value
}
],
"value": "steelblue" // Default color
}
}
},
{
"mark": {"type": "text", "dy": -10, "fontWeight": "bold"},
"encoding": {
"x": {"field": "a", "type": "nominal"},
"y": {"field": "b", "type": "quantitative", "stack": null},
"text": {
"field": "b",
"type": "quantitative",
"format": "0,"
},
"color": {"value": "black"} // Text color
}
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment