更改 Jupyter Notebook 中 Altair 图渲染的大小

Changing the size of Altair plot renders in Jupyter notebook

我在 Jupyter notebook(不是 JupyterLab)中渲染 Altair 图使用:

alt.renderers.enable('notebook')

一切正常,但是相对于我的 Jupyter notebook 的宽度,绘图通常很小。

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

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

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

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

谢谢!

无法将 Altair 图表自动缩放到浏览器的大小 window。图表的大小由图表规范中的 view configuration and/or、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 documentation,您可以将 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'
)

N.b.:这适用于标准alt.Chart.save方法,因为内置-在 HTML 模板中没有预期响应式样式。

以下是我如何将它变成 运行 的相关片段(在标准 Flask/Jinja2 堆栈中 - 您可以使用 IPython.display.displayIPython.display.HTML):

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 选择器来自检查元素,而不是按规范,所以它会中断
  • 高度不随宽度变化。你需要。一个合理的价值。