为何Jupyter Notebook无法显示交互式图表?
Great question! The difference boils down to how these two Jupyter environments handle interactive visualization rendering:
The Root Cause
Jupyter Lab comes built-in with native support for Vega-Lite (the underlying framework Altair uses to create charts). This means it can directly interpret and render Altair's interactive outputs without extra setup.
Classic Jupyter Notebook, on the other hand, doesn't include this native Vega-Lite support out of the box. Without the right configuration, it just displays the text representation of the VegaLite object (the "VegaLite 2 object" you saw) instead of rendering the actual chart.
Fixes to Get Your Charts Showing
Option 1: Enable Altair's Notebook Renderer
This is the most straightforward method if you want full interactive functionality:
- First, install the required dependencies (if you haven't already):
pip install altair vega_datasets ipyvega - Add one line to your code to enable the notebook renderer before creating your chart:
Run the cell again, and you should see your interactive chart load up.import altair as alt alt.renderers.enable('notebook') # This is the key line! from vega_datasets import data source = data.cars() alt.Chart(source).mark_point().encode( x='Horsepower', y='Miles_per_Gallon', size='Acceleration' )
Option 2: Render as HTML (No Extra Extension Needed)
If you don't want to install ipyvega, you can have Altair generate an HTML version of the chart and display it using IPython's built-in tools:
import altair as alt from vega_datasets import data from IPython.display import HTML source = data.cars() chart = alt.Chart(source).mark_point().encode( x='Horsepower', y='Miles_per_Gallon', size='Acceleration' ) # Convert the chart to HTML and display it HTML(chart.to_html())
This will render the interactive chart directly in your notebook cell without needing any special extensions.
Quick Note on Version Compatibility
Make sure you're using a recent, stable version of Altair (v4.x or later is recommended). Older versions might have compatibility issues with newer Jupyter Notebook releases. You can update Altair with:
pip install --upgrade altair
内容的提问来源于stack exchange,提问作者Emanuel Fontelles

