Skip to content

Instantly share code, notes, and snippets.

@sacundim
Last active May 27, 2020 05:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sacundim/8161ae8a26b95fd4686a8154fcf9bed2 to your computer and use it in GitHub Desktop.
Save sacundim/8161ae8a26b95fd4686a8154fcf9bed2 to your computer and use it in GitHub Desktop.
Vega-Lite: Making overlay text look good on a diverging scale
{
"$schema": "https://vega.github.io/schema/vega-lite/v4.json",
"data": {"url": "data/cars.json"},
"transform": [
{
"aggregate": [{"op": "count", "as": "num_cars"}],
"groupby": ["Origin", "Cylinders"]
}
],
"encoding": {
"y": {"field": "Origin", "type": "ordinal"},
"x": {"field": "Cylinders", "type": "ordinal"}
},
"layer": [
{
"mark": "rect",
"encoding": {
"color": {
"field": "num_cars",
"type": "quantitative",
"title": "Count of Records",
"legend": {"direction": "horizontal", "gradientLength": 120},
"scale": {
"scheme": "redblue"
}
}
}
},
{
"mark": "text",
"encoding": {
"text": {"field": "num_cars", "type": "quantitative"},
"color": {
"condition": {"test": "27.75 < datum['num_cars'] & datum['num_cars'] < 81.75", "value": "black"},
"value": "white"
}
}
}
],
"config": {
"axis": {"grid": true, "tickBand": "extent"}
}
}
{
"$schema": "https://vega.github.io/schema/vega-lite/v4.json",
"data": {"url": "data/cars.json"},
"transform": [
{
"aggregate": [{"op": "count", "as": "num_cars"}],
"groupby": ["Origin", "Cylinders"]
},
{
"joinaggregate": [
{
"op": "min",
"field": "num_cars",
"as": "num_cars_min"
},
{
"op": "max",
"field": "num_cars",
"as": "num_cars_max"
}
]
},
{
"calculate": "(datum.num_cars_min + datum.num_cars_max) * 0.25",
"as": "lo_mid"
},
{
"calculate": "(datum.num_cars_min + datum.num_cars_max) * 0.75",
"as": "hi_mid"
}
],
"encoding": {
"y": {"field": "Origin", "type": "ordinal"},
"x": {"field": "Cylinders", "type": "ordinal"}
},
"layer": [
{
"mark": "rect",
"encoding": {
"color": {
"field": "num_cars",
"type": "quantitative",
"title": "Count of Records",
"legend": {"direction": "horizontal", "gradientLength": 120},
"scale": {
"scheme": "redblue"
}
}
}
},
{
"mark": "text",
"encoding": {
"text": {"field": "num_cars", "type": "quantitative"},
"color": {
"condition": {
"test": "datum['lo_mid'] < datum['num_cars'] & datum['num_cars'] < datum['hi_mid']",
"value": "black"
},
"value": "white"
}
}
}
],
"config": {
"axis": {"grid": true, "tickBand": "extent"}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment