我正在使用以下方法在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地块不会相应缩放(它们保持相同大小)。
有什么方法可以缩放渲染图的大小(即使其变大),同时仍将其保留在笔记本中?
谢谢!
答案 0 :(得分:2)
无法将Altair图表自动缩放到浏览器窗口的大小。图表的大小由图表规范中的view configuration和/或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
)
答案 1 :(得分:0)
只需将其记录在这里,因为我遇到了同样的问题并找到了解决方法:
根据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'
)
Nb。:这与标准alt.Chart.save
方法不兼容,因为内置HTML模板无法预期响应样式。
以下是我如何运行它的相关摘要(在标准的Flask / Jinja2堆栈中-您可以使用IPython.display.display
和IPython.display.HTML
将其修改为在Jupyter笔记本中运行):
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
确保我们标记为div
的{{1}}的大小正确
class="altair"
答案 2 :(得分:0)
您可以使用与缩放笔记本相同的方法,但适用于 Altair 图表。
from IPython.display import HTML,display
css_str = '<style>.chart-wrapper canvas {width:90% !important}</style>'
display(HTML(css_str))
一些陷阱: