Reputation: 11
I would like to create a Vega-Lite / Deneb faceted bar chart with data where there is a need to a) have a specific color for each bar ie Brand and b) have the Brands in a specific order. Color and sort order are given as columns in the data: bColor & bSort. Is there a way to use the color field AND have a legend?
If I hard-code the colors as a range:
"scale": {"range": ["red", "orange", "green"]}
then I can see also the legend. So, is there a way to create a list of (unique) colors in the correct order to be used as the range? I have tried for example
"scale": {"range": {"op": "min", "field": "bColor"}},
but it gives me an error: Undefined data set name: "data_1"
Edit: This is how the end results should look like (this is done with hard-coded color range): chart with legend
Upvotes: 1
Views: 609
Reputation: 30174
Changing resolve from independent to shared breaks the chart.
{
"$schema": "https://vega.github.io/schema/vega-lite/v5.json",
"description": "dedicated colors and sort order",
"data": {
"values": [
{
"Brand": "Brand A (orange)",
"Statement": "S1",
"Score": 0.6,
"bSort": 2,
"bColor": "orange"
},
{
"Brand": "Brand B (green)",
"Statement": "S1",
"Score": 0.5,
"bSort": 3,
"bColor": "green"
},
{
"Brand": "Brand C (red)",
"Statement": "S1",
"Score": 0.7,
"bSort": 1,
"bColor": "red"
},
{
"Brand": "Brand A (orange)",
"Statement": "S2",
"Score": 0.6,
"bSort": 2,
"bColor": "orange"
},
{
"Brand": "Brand B (green)",
"Statement": "S2",
"Score": 0.5,
"bSort": 3,
"bColor": "green"
},
{
"Brand": "Brand C (red)",
"Statement": "S2",
"Score": 0.7,
"bSort": 1,
"bColor": "red"
},
{
"Brand": "Brand A (orange)",
"Statement": "S3",
"Score": 0.6,
"bSort": 2,
"bColor": "orange"
},
{
"Brand": "Brand B (green)",
"Statement": "S3",
"Score": 0.5,
"bSort": 3,
"bColor": "green"
},
{
"Brand": "Brand C (red)",
"Statement": "S3",
"Score": 0.7,
"bSort": 1,
"bColor": "red"
},
{
"Brand": "Brand A (orange)",
"Statement": "S4",
"Score": 0.6,
"bSort": 2,
"bColor": "orange"
},
{
"Brand": "Brand B (green)",
"Statement": "S4",
"Score": 0.5,
"bSort": 3,
"bColor": "green"
},
{
"Brand": "Brand C (red)",
"Statement": "S4",
"Score": 0.7,
"bSort": 1,
"bColor": "red"
}
]
},
"resolve": { "scale": {"color": "independent"}},
"facet": {"field": "Statement"},
"columns": 2,
"spec": {
"encoding": {
"x": {"field": "Score", "type": "quantitative"},
"y": {"field": "Brand"},
"color": {"field": "bColor", "scale": {"range": {"field": "bColor"}}}
},
"mark": {"type": "bar", "tooltip": true}
}
}
Upvotes: 1