脚本
我正在使用Altair用python制作图表。但是,当我将图表保存为HTML并打开文件时,呈现的图表是不同的。特别是,图例在HTML文件中是水平的,而在Jupyter笔记本中呈现时它是垂直的。更重要的是,当我使用在HTML中创建的链接来使用Vega编辑器时,它再次以垂直图例呈现。
使vega lite呈现为垂直图例的HTML缺少什么?
我的Python代码
import altair as alt
import json
chart = alt.Chart.from_dict(json.loads("""
{
"config": {"view": {"width": 400, "height": 300}},
"data": {
"values": [
{"X": "Thing1", "Y": "ThatA", "Value": 1},
{"X": "Thing1", "Y": "ThatB", "Value": 3},
{"X": "Thing2", "Y": "ThatA", "Value": 2},
{"X": "Thing2", "Y": "ThatB", "Value": 4}
]
},
"mark": "bar",
"encoding": {
"color": {"type": "quantitative", "field": "Value"},
"x": {"type": "nominal", "field": "X"},
"y": {"type": "nominal", "field": "Y"}
},
"height": 300,
"width": 500,
"$schema": "https://vega.github.io/schema/vega-lite/v2.4.3.json"
}"""
))
chart
呈现为
保存
chart.savechart('test.html')
生产
<!DOCTYPE html>
<html>
<head>
<style>
.vega-actions a {
margin-right: 12px;
color: #757575;
font-weight: normal;
font-size: 13px;
}
.error {
color: red;
}
</style>
<script src="https://cdn.jsdelivr.net/npm//vega@3.3.1"></script>
<script src="https://cdn.jsdelivr.net/npm//vega-lite@2.4.3"></script>
<script src="https://cdn.jsdelivr.net/npm//vega-embed@3.11"></script>
</head>
<body>
<div id="vis"></div>
<script type="text/javascript">
var spec = {"config": {"view": {"width": 400, "height": 300}}, "data": {"values": [{"X": "Thing1", "Y": "ThatA", "Value": 1}, {"X": "Thing1", "Y": "ThatB", "Value": 3}, {"X": "Thing2", "Y": "ThatA", "Value": 2}, {"X": "Thing2", "Y": "ThatB", "Value": 4}]}, "mark": "bar", "encoding": {"color": {"type": "quantitative", "field": "Value"}, "x": {"type": "nominal", "field": "X"}, "y": {"type": "nominal", "field": "Y"}}, "height": 300, "width": 500, "$schema": "https://vega.github.io/schema/vega-lite/v2.4.3.json"};
var embed_opt = {"mode": "vega-lite"};
function showError(el, error){
el.innerHTML = ('<div class="error">'
+ '<p>JavaScript Error: ' + error.message + '</p>'
+ "<p>This usually means there's a typo in your chart specification. "
+ "See the javascript console for the full traceback.</p>"
+ '</div>');
throw error;
}
const el = document.getElementById('vis');
vegaEmbed("#vis", spec, embed_opt)
.catch(error => showError(el, error));
</script>
</body>
</html>
如果运行该片段,您将看到一个带有水平图例的图表。如果按照链接进行编辑,您将再次看到一个垂直图例,如下所示: