[英]Control canvas size with altair / vega-lite / vega-embed
我正在使用 vega-lite 构建图形,并使用 vega-embed 在 DOM 中渲染它们。 我喜欢这些工具和抽象,但我仍在弄清楚其中一些是如何工作的。
我正在开发一个应用程序,其中控制画布的确切大小很重要。 不幸的是,当我指定(例如)
bars = alt.Chart(df).mark_bar().encode(
x='bins:O',
y="weights:Q"
).properties(width=240, height=200)
我得到一个看起来像这样的图表对象:
{
"$schema": "https://vega.github.io/schema/vega-lite/v2.6.0.json",
"config": {
"view": {
"height": 300,
"width": 400
}
},
"data": {
"name": "data-a681d02fb484e64eadd9721b37015d5b"
},
"datasets": {
"data-a681d02fb484e64eadd9721b37015d5b": [
{
"bins": 3.7,
"weights": 5.555555555555555
},
{
"bins": 10.8,
"weights": 3.439153439153439
},
{
"bins": 17.9,
"weights": 17.857142857142858
},
{
"bins": 25.0,
"weights": 24.206349206349206
},
{
"bins": 32.0,
"weights": 16.137566137566136
},
{
"bins": 39.1,
"weights": 12.3015873015873
},
{
"bins": 46.2,
"weights": 9.788359788359788
},
{
"bins": 53.3,
"weights": 5.423280423280423
},
{
"bins": 60.4,
"weights": 3.439153439153439
},
{
"bins": 67.5,
"weights": 1.8518518518518516
}
]
},
"encoding": {
"x": {
"field": "bins",
"type": "ordinal"
},
"y": {
"field": "weights",
"type": "quantitative"
}
},
"height": 200,
"mark": "bar",
"width": 240
}
(注意 config.view 中不同的高度和宽度。)
我正在像这样渲染 HTML:
<div id="my_id"></div>
<script>
const vlSpec = my_chart_obj;
vegaEmbed('#my_id', vlSpec, {
actions: false
}).then(result=>console.log(result)).catch(console.warn);
</script>
这产生:
<div id="my-id" class="vega-embed">
<canvas width="284" height="252" class="marks"></canvas>
<div class="vega-bindings"></div>
</div>
注意: width="284" height="252"
看起来宽度和高度被填充,但我不知道为什么或如何。
图表本身看起来很可爱,只是它的大小不正确并因此弄乱了我的布局。
帮助!
config.view
中的宽度和高度由 Altair 的默认主题设置,对您上面创建的图表没有影响,因为它们被图表级别的width
和height
属性覆盖。
如果您觉得从图表中删除此配置会更好,您可以运行
alt.themes.enable('none')
清除默认图表主题( alt.themes.enable('default')
将恢复默认值)。
关于画布的大小:默认情况下,图表width
和height
属性控制图表面板本身的大小,不包括轴标签和标题的额外填充。 如果您希望整个画布适合指定的边界,包括标签填充,您可以通过autosize属性指定它; 例如:
alt.Chart(df).mark_bar().encode(
x='bins:O',
y="weights:Q"
).properties(
width=240,
height=200,
autosize=alt.AutoSizeParams(
type='fit',
contains='padding'
)
)
但请注意,这不适用于每种图表类型; 有关更多信息,请参阅自动调整大小限制。
如果因为我的标签被切断而为此挣扎。
确保为自动调整添加填充值,以便在包含标签的情况下正常工作。
.properties(
width=800,
height=600,
padding=100,
autosize=alt.AutoSizeParams(
type='pad',
contains='padding'
)
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.