[英]How to define repeat and layer in vega-lite api
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
.我想用vega-lite-api可视化这些数据,这样 X 轴就会有学生,并且
d
和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:这正确地显示了 y 轴上的
d
列值与 x 轴上的学生:
However, I am unable to guess how I can have column e
values on y axis too.但是,我无法猜测我如何在 y 轴上也有列
e
值。 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.但我无法猜测如何将上述 vega-lite 语法中的
repeat
和layer
翻译成 vega-lite-api 调用。
According to the documentation you can use the vl.repeat
and vl.layer
methods to build repeat
and layer
objects.根据文档,您可以使用
vl.repeat
和vl.layer
方法来构建repeat
和layer
对象。
You can then insert these into your spec with the spec.repeat
method returned by vl.encode() , and with the y.field method.然后,您可以使用vl.encode()返回的
spec.repeat
方法和y.field方法将它们插入到您的规范中。
Using your example, the following JS code使用您的示例,以下 JS 代码
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:将 output 这个 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.此笔记本将让您试验此代码的实时版本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.