问题
I have the following minimal data:
[
{"date": "2019-01-01", "foo": 10000, "bar": 10, "goo": 30},
{"date": "2019-01-02", "foo": 30000, "bar": 20, "goo": 20},
{"date": "2019-01-03", "foo": 40000, "bar": 20, "goo": 10},
{"date": "2019-01-04", "foo": 1000, "bar": 60, "goo": 20}
]
Which I plot using VEGA-LITE:
<!DOCTYPE html>
<html>
<head>
<title>Embedding Vega-Lite</title>
<script src="https://cdn.jsdelivr.net/npm/vega@5.4.0"></script>
<script src="https://cdn.jsdelivr.net/npm/vega-lite@3.3.0"></script>
<script src="https://cdn.jsdelivr.net/npm/vega-embed@4.2.0"></script>
</head>
<body>
<div id="vis"></div>
<script type="text/javascript">
var yourVlSpec = {
"$schema": "https://vega.github.io/schema/vega-lite/v3.json",
"Title": "Insights stats",
"description": "Overview of insights stats",
"width": 1000,
"height": 450,
"data": {
"url": "./data.json"
},
"layer": [
{
"mark": "line",
"encoding": {
"x": {
"field": "date",
"type": "temporal",
"title": "Date"
},
"y": {
"field": "foo",
"type": "quantitative",
"title": "Some Foo"
}
}
},
{
"mark": {
"type": "line",
"stroke": "firebrick"
},
"encoding": {
"x": {
"field": "date",
"type": "temporal"
},
"y": {
"field": "bar",
"type": "quantitative",
"title": null,
"scale": { "domain": [0, 100] }
}
}
},
{
"mark": {
"type": "line",
"stroke": "red"
},
"encoding": {
"x": {
"field": "date",
"type": "temporal"
},
"y": {
"field": "goo",
"type": "quantitative",
"title": "Ratio (%)",
"scale": { "domain": [0, 100] }
}
}
}
],
"resolve": { "scale": { "y": "independent" } }
};
vegaEmbed('#vis', yourVlSpec);
</script>
</body>
</html>
I fail to have a proper legend for each line. What am I missing?
回答1:
Vega-Lite will generate a legend for a chart if there is an encoding that warrants it, such as color, shape, etc.
In the case of plotting multiple columns, a useful pattern is to use the Fold Transform in order to specify your colors via an encoding rather than by manual layering. The result looks something like this (vega editor link):
{
"$schema": "https://vega.github.io/schema/vega-lite/v3.json",
"title": "Insights stats",
"description": "Overview of insights stats",
"width": 1000,
"height": 450,
"data": {
"values": [
{"date": "2019-01-01", "foo": 10, "bar": 10, "goo": 30},
{"date": "2019-01-02", "foo": 30, "bar": 20, "goo": 20},
{"date": "2019-01-03", "foo": 40, "bar": 20, "goo": 10},
{"date": "2019-01-04", "foo": 1, "bar": 60, "goo": 20}
]
},
"transform": [
{"fold": ["foo", "bar", "goo"]}
],
"mark": "line",
"encoding": {
"x": {"field": "date", "type": "temporal"},
"y": {"field": "value", "type": "quantitative"},
"color": {"field": "key", "type": "nominal"}
}
}
来源:https://stackoverflow.com/questions/56425430/plot-multiple-columns-with-vega-lite-and-include-a-legend