I have a data which looks something like this:
student_name,d,e
student1,0.1,0.7
student2,0.2,0.3
student3,0.3,0.4
student4,0.25,0.2
student5,0.4,0.15
student6,0.6,0.2
student7,0.15,0.5
student8,0.7,0.13
student9,0.56,0.22
student10,0.35,0.2
I want to visualize this data with vega-lite-api such that X-axis will have students and there will be two line charts each for column d
and e
. I tried something like this :
vl
.markLine()
.encode(
vl.x().fieldN('student_name').sort('y'),
vl.y().fieldQ('d'),
);
This correctly shows column d
values on y axis against students on x axis:
However, I am unable to guess how I can have column e
values on y axis too. I guess I need to repeat and layer, something like this :
{
"$schema": "https://vega.github.io/schema/vega-lite/v5.json",
"data": {
"url": "data/movies.json"
},
"repeat": {
"layer": ["US Gross", "Worldwide Gross"]
},
"spec": {
"mark": "line",
"encoding": {
"x": {
"bin": true,
"field": "IMDB Rating",
"type": "quantitative"
},
"y": {
"aggregate": "mean",
"field": {"repeat": "layer"},
"type": "quantitative",
"title": "Mean of US and Worldwide Gross"
},
"color": {
"datum": {"repeat": "layer"},
"type": "nominal"
}
}
}
}
which outputs:
But I am unable to guess how can translate repeat
and layer
in above vega-lite grammar to vega-lite-api calls.
According to the documentation you can use the vl.repeat
and vl.layer
methods to build repeat
and layer
objects.
You can then insert these into your spec with the spec.repeat
method returned by vl.encode() , and with the y.field method.
Using your example, the following JS code
vl
.markLine()
.encode(
vl.x().fieldN('student_name').sort('y'),
vl.y().field(vl.repeat('layer')),
).repeat(
vl.layer(["d", "e"])
)
will output this JSON:
{
"$schema":"https://vega.github.io/schema/vega-lite/v4.json",
"repeat":{
"layer":[
"d",
"e"
]
},
"spec":{
"mark":{
"type":"line"
},
"encoding":{
"x":{
"field":"student_name",
"type":"nominal",
"sort":"y"
},
"y":{
"field":{
"repeat":"layer"
}
}
}
}
}
This notebook will let you experiment with a live version of this code.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.