[英]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 圖表自動縮放到瀏覽器窗口的大小。 圖表的大小由圖表規范中的視圖配置和/或width
和height
屬性控制; 例如:
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.display
和IPython.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))
一些陷阱:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.