我正在使用Altair在python中生成图表。但是,当我将图表保存为HTML并打开文件时,呈现的图表有所不同。特别是,在我的Jupyter Notebook中渲染时,图例在HTML文件中是水平的,而它是垂直的。而且,当我使用在HTML中创建的链接使用Vega编辑器时,它再次使用垂直图例进行渲染。
用垂直图例制作vega-lite渲染的HTML中缺少什么?
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>
如果运行该代码段,则会看到带有水平图例的图表。如果您点击链接进行编辑,则会再次看到垂直图例,如下所示:
答案 0 :(得分:1)
Vega-Lite更改了其在2.5版中渲染图例的方式。以前,连续的图例是垂直的,而在2.5及更高版本中,图例是水平的。因此,问题的根源在于,在两种情况下您使用的是Vega-Lite的不同版本。
JupyterLab或Jupyter笔记本前端使用的vega-lite版本由前端扩展控制,该扩展不属于Altair库。如果您需要更新的渲染器,则可以更新前端扩展名(如果使用JupyterLab,则为vega-extension;如果使用Jupyter笔记本,则为ipyvega package)。
另一方面,当您调用save()
时,它会生成不依赖于前端的HTML,但是会从网络上加载最新的javascript库。
如果您想在Vega-Lite 2.5或更高版本中明确选择垂直图例方向,则可以在颜色编码中使用"legend": {"direction": "vertical"}
。