Reputation: 2101
I have this bar chart in vega lite in my Observable notebook
But I want to add a color scale to the bars so that the smallest numbers are red and the largest numbers are green and the numbers in between are yellow.
In order to do this -- I was thinking of setting up an ordinal scale with the domain as [0,5]
since the numbers range from 0 to 5. The range of that scale would be ["red", "yellow", "green"]
. But I'm just not sure how to apply that ordinal color scale to a vega lite chart. My code is below
barchart = vegalite ({
"data": {"values": barChartData},
"height": {"step": 17},
"title": "Gold",
"encoding": {
"y": {
"field": "program",
"type": "ordinal",
"sort": "-x"
},
"x": {
"aggregate": "sum",
"field": "index",
"title": "Gold",
"axis": null
}
},
"layer": [{
"mark": "bar"
}, {
"mark": {
"type": "text",
"align": "left",
"baseline": "middle",
"dx": 3
},
"encoding": {
"text": {"field": "index", "type": "quantitative"}
}
}]
})
Upvotes: 0
Views: 1387
Reputation: 2416
Provide color
or fill
encoding in your bar chart and add your color as scales
as done below or in editor:
var yourVlSpec = {
"$schema": "https://vega.github.io/schema/vega-lite/v5.json",
"description": "A simple bar chart with embedded data.",
"data": {
"values": [{
"index": 0.03,
"program": "Deliciousness"
},
{
"index": 0.43,
"program": "Reno 911!"
},
{
"index": 0.07,
"program": "Curious Life and Death of"
},
{
"index": 0.01,
"program": "True Life"
},
{
"index": 4.21,
"program": "Two and a Half Men"
},
{
"index": 0.06,
"program": "How Far is Tattoo Far"
},
{
"index": 0.39,
"program": "Cheaters"
},
{
"index": 4.72,
"program": "Bar Rescue"
},
{
"index": 0.81,
"program": "Key & Peele"
},
{
"index": 0.25,
"program": "Drunk History"
},
{
"index": 1.32,
"program": "Tosh.O"
},
{
"index": 0.11,
"program": "Revenge Prank"
},
{
"index": 4.88,
"program": "Workaholics"
},
{
"index": 0.04,
"program": "My Wife and Kids"
},
{
"index": 0.05,
"program": "World of Weapons"
},
{
"index": 0.03,
"program": "Roseanne"
},
{
"index": 1.98,
"program": "Everybody Loves Raymond"
},
{
"index": 1.2,
"program": "Aerial America"
}
]
},
"height": {
"step": 17
},
"title": "Gold",
"encoding": {
"y": {
"field": "program",
"type": "ordinal",
"sort": "-x"
},
"x": {
"aggregate": "sum",
"field": "index",
"title": "Gold",
"axis": null
}
},
"layer": [{
"mark": "bar",
"encoding": {
"color": {
"field": "index",
"scale": {
"range": ["red", "yellow", "green"],
"type": "linear"
},
"legend": null
}
}
},
{
"mark": {
"type": "text",
"align": "left",
"baseline": "middle",
"dx": 3
},
"encoding": {
"text": {
"field": "index",
"type": "quantitative"
}
}
}
]
};
vegaEmbed("#vis", yourVlSpec);
<script src="https://cdn.jsdelivr.net/combine/npm/[email protected],npm/[email protected],npm/[email protected]"></script>
<body>
<div id="vis"></div>
</body>
Upvotes: 1