My code is as follows;
{ "$schema": "https://vega.github.io/schema/vega-lite/v5.json", "width": 800, "height": 200, "data": { "values": [ { "pre_120": 0, "pre_90": 0, "pre_60": 0, "post_60": 100, "post_90": 150, "post_120": 200, "type": "Mango", "count": "twenty" }, { "pre_120": 0, "pre_90": 0, "pre_60": 0, "post_60": 90, "post_90": 140, "post_120": 190, "type": "Apple", "count": "ten" } ] }, "transform": [ {"fold": ["pre_120", "pre_90", "pre_60","0", "post_60", "post_90", "post_120"]} ], "layer": [ { "mark": "line", "encoding": { "x": { "field": "key", "sort": [ "pre_120", "pre_90", "pre_60", "0", "post_60", "post_90", "post_120" ] }, "y": {"field": "value", "type": "quantitative"}, "color": {"field": "type", "type": "nominal"} } }, { "mark": { "type": "rule", "color": "maroon", "size": 3 , "strokeDash": [6, 4]}, "encoding": { "x": { "datum": "0" } } } ] }
Below is the link to the vega editor.
https://vega.github.io/editor/#/gist/947b2a99801bc6a08d468cdb9acbeb50/legend.json
My aim is to show the legend to include value of 2 fields i.e. type and count fields with a hyphen.
Example :
In the image below, I wanted to show the legends as
‘Apple – twenty’
and
‘Mango – ten’
How could I do the same?
Advertisement
Answer
I would just create a new calculated field and use that.
{ "$schema": "https://vega.github.io/schema/vega-lite/v5.json", "width": 800, "height": 200, "data": { "values": [ { "pre_120": 0, "pre_90": 0, "pre_60": 0, "post_60": 100, "post_90": 150, "post_120": 200, "type": "Mango", "count": "ten" }, { "pre_120": 0, "pre_90": 0, "pre_60": 0, "post_60": 90, "post_90": 140, "post_120": 190, "type": "Apple", "count": "twenty" } ] }, "transform": [ {"fold": ["pre_120", "pre_90", "pre_60", "post_60", "post_90", "post_120"]}, {"calculate": "datum.type + ' - ' + datum.count", "as": "label"} ], "layer": [ { "mark": "line", "encoding": { "x": { "field": "key", "sort": [ "pre_120", "pre_90", "pre_60", "post_60", "post_90", "post_120" ] }, "y": {"field": "value", "type": "quantitative"}, "color": { "field": "label", "type": "nominal" } } } ] }