My code is as follows;
JavaScript
x
65
65
1
{
2
"$schema": "https://vega.github.io/schema/vega-lite/v5.json",
3
"width": 800,
4
"height": 200,
5
"data": {
6
"values": [
7
{
8
"pre_120": 0,
9
"pre_90": 0,
10
"pre_60": 0,
11
"post_60": 100,
12
"post_90": 150,
13
"post_120": 200,
14
"type": "Mango",
15
"count": "twenty"
16
},
17
{
18
"pre_120": 0,
19
"pre_90": 0,
20
"pre_60": 0,
21
"post_60": 90,
22
"post_90": 140,
23
"post_120": 190,
24
"type": "Apple",
25
"count": "ten"
26
}
27
]
28
},
29
"transform": [
30
{"fold": ["pre_120", "pre_90", "pre_60","0", "post_60", "post_90", "post_120"]}
31
],
32
"layer": [
33
{
34
"mark": "line",
35
"encoding": {
36
"x": {
37
"field": "key",
38
"sort": [
39
"pre_120",
40
"pre_90",
41
"pre_60",
42
"0",
43
"post_60",
44
"post_90",
45
"post_120"
46
]
47
},
48
"y": {"field": "value", "type": "quantitative"},
49
"color": {"field": "type", "type": "nominal"}
50
}
51
},
52
{
53
"mark": {
54
"type": "rule",
55
"color": "maroon",
56
"size": 3 ,
57
"strokeDash": [6, 4]},
58
"encoding": {
59
"x": { "datum": "0" }
60
}
61
}
62
]
63
}
64
65
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.
JavaScript
1
57
57
1
{
2
"$schema": "https://vega.github.io/schema/vega-lite/v5.json",
3
"width": 800,
4
"height": 200,
5
"data": {
6
"values": [
7
{
8
"pre_120": 0,
9
"pre_90": 0,
10
"pre_60": 0,
11
"post_60": 100,
12
"post_90": 150,
13
"post_120": 200,
14
"type": "Mango",
15
"count": "ten"
16
},
17
{
18
"pre_120": 0,
19
"pre_90": 0,
20
"pre_60": 0,
21
"post_60": 90,
22
"post_90": 140,
23
"post_120": 190,
24
"type": "Apple",
25
"count": "twenty"
26
}
27
]
28
},
29
"transform": [
30
{"fold": ["pre_120", "pre_90", "pre_60", "post_60", "post_90", "post_120"]},
31
{"calculate": "datum.type + ' - ' + datum.count", "as": "label"}
32
],
33
"layer": [
34
{
35
"mark": "line",
36
"encoding": {
37
"x": {
38
"field": "key",
39
"sort": [
40
"pre_120",
41
"pre_90",
42
"pre_60",
43
"post_60",
44
"post_90",
45
"post_120"
46
]
47
},
48
"y": {"field": "value", "type": "quantitative"},
49
"color": {
50
"field": "label",
51
"type": "nominal"
52
}
53
}
54
}
55
]
56
}
57