将 Panel 和 Altair 交互式图表另存为 HTML

Saving Panel and Altair interactive charts as HTML

我使用创建了一个 Panel 和 Altair 交互式图表。

from bokeh.resources import INLINE, CDN
from vega_datasets import data
import panel as pn
import pandas as pd
import altair as alt
from altair import datum
cars = data.cars()

alt.renderers.enable('altair_viewer')
alt.data_transformers.enable('default')
pn.extension('vega')
options= cars['Origin'].unique().tolist()
hp_range_slider = pn.widgets.RangeSlider(
    name='Range Slider', start=40, end=250, value=(60, 160), step=10)
country_ticker = pn.widgets.MultiSelect(name='MultiSelect', value=[options[0], options[1]],
    options=options, size=8)
@pn.depends(country_ticker.param.value, hp_range_slider.param.value)
def get_plot(country_ticker, hp_range):
    df=cars.copy()
    start_hp = hp_range_slider.value[0]
    end_hp = hp_range_slider.value[1]
    mask = (df['Horsepower'] > start_hp) & (df['Horsepower'] <= end_hp)  # create filter mask for the dataframe
    df = df.loc[mask]  # filter the dataframe
    print(country_ticker)
    print(start_hp,end_hp)
    # create the Altair chart object
    scatter = alt.Chart(df).mark_point().encode(
        x='Horsepower:Q',
        y='Miles_per_Gallon:Q',
        color='Origin:N'
    ).transform_filter(
        alt.FieldOneOfPredicate(field='Origin', oneOf=country_ticker)
    )
    return scatter
title = '## Horsepower Dashboard'
subtitle = 'This dashboard allows you to select a country and HP range .'


dashboard = pn.Row(
    pn.Column(title, subtitle, country_ticker, hp_range_slider),
    get_plot # draw chart function!
)
dashboard.servable()

dashboard.save("test_altair.html",embed=True,resources=INLINE)
dashboard.show()

当我执行dashboard.show 命令时,它显示完美。

但是当我将其另存为 html 时,我没有得到图表,只有面板组件。有什么帮助吗?

altair_viewer 渲染器需要实时内核。来自 altiar_viewer README

Note that the display based on altair viewer will only function correctly as long as the kernel that created the charts is running, as it depends on the background server started by the kernel.

如果您希望已保存HTML中的图表在没有内核的情况下显示,您需要使用不同的渲染器,例如默认渲染器。有关渲染器的更多信息,请参阅 Displaying Altair Charts