繁体   English   中英

在 Jupyter 笔记本中更改 Altair 绘图的大小

[英]Changing the size of Altair plot renders in Jupyter notebook

我在 Jupyter 笔记本(不是 JupyterLab)中使用以下方法渲染 Altair 图:

alt.renderers.enable('notebook')

一切正常,但是相对于我的 Jupyter 笔记本的宽度,这些图通常很小。

如果我使用以下方法将笔记本的宽度扩展到屏幕的 100%:

from IPython.core.display import display, HTML
display(HTML("<style>.container { width:100% !important; }</style>"))

Altair 图不会相应地缩放(它们保持相同的大小)。

有什么方法可以缩放渲染图的大小(即,使它们更大),同时仍将它们保留在笔记本中?

谢谢!

无法将 Altair 图表自动缩放到浏览器窗口的大小。 图表的大小由图表规范中的视图配置和/或widthheight属性控制; 例如:

import altair as alt
from vega_datasets import data
cars = data.cars()

alt.Chart(cars).mark_point().encode(
    x='Horsepower',
    y='Miles_per_Gallon',
    color='Origin'
).properties(
    width=800,
    height=300
)

在此处输入图片说明

只是在这里记录,因为我遇到了同样的问题并找到了解决方案:

根据Vega 文档,您可以将width设置为container ,这会将图表大小调整为周围的 HTML 容器。

import altair as alt
from vega_datasets import data
cars = data.cars()

alt.Chart(cars).mark_point().encode(
    x='Horsepower',
    y='Miles_per_Gallon',
    color='Origin'
).properties(
    width='container'
)

注意:这符合标准工作alt.Chart.save方法,如内置的HTML模板不预期响应造型。

这是我如何运行它的相关片段(在标准 Flask/Jinja2 堆栈中 - 您可以使用IPython.display.displayIPython.display.HTML调整它以在 Jupyter notebook 中运行):

app.py

通过呈现 HTML 模板来提供图表,其中包含图表作为表示 Vega 规范的 JSON 对象(Vega 是呈现 Altair 图表的底层 JavaScript 库)。

@app.route('/chart')
def chart():
    the_chart = alt.Chart(...).properties(width='container')
    return render_template('chart.html.jinja2', chart=the_chart.to_json())

chart.html.jinja2

嵌入图表的模板

...

<!-- anchor point: this is an empty `div` that will be filled with the chart -->
<div id="chart_pl" class="altair"></div>

...

<!-- import vega libraries -->
<script src="https://cdn.jsdelivr.net/npm/vega@5"></script>
<script src="https://cdn.jsdelivr.net/npm/vega-lite@4"></script>
<script src="https://cdn.jsdelivr.net/npm/vega-embed@6"></script>

<!-- render the chart with vega -->
<script type="text/javascript">
    <!-- the JSON object needs to mark as `safe` so it doesn't get HTML-quoted -->
    var spec = {{ chart|safe }};
    <!-- some vega options -->
    var opt = {"renderer": "canvas", "actions": false};
    <!-- embed the chart into div with ID "chart" -->
    vegaEmbed("#chart", spec, opt);
</script>

style.css

确保我们标记为class="altair"div大小合适

.altair {
    width: 100%;
}

您可以使用与缩放笔记本相同的方法,但适用于 Altair 图表。

from IPython.display import HTML,display
css_str = '<style>.chart-wrapper canvas {width:90% !important}</style>'
display(HTML(css_str))

一些陷阱:

  • CSS 选择器来自检查元素,而不是通过规范,所以它会破坏
  • 高度不随宽度缩放。 你需要。 一个合理的价值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM