Jupyter Notebook中执行init_notebook_mode(connected=True)代码失败求助
init_notebook_mode(connected=True) Error in Jupyter Notebook for Plotly Geographic Visualizations Hey there! Let's troubleshoot why that line is failing and get your geographic plots up and running smoothly. Here are the most common fixes to try:
1. Drop the Deprecated connected=True Parameter
In newer Plotly versions (4.x and above), the connected parameter for init_notebook_mode() has been completely deprecated. Calling the function without this parameter should resolve the error immediately:
from plotly.offline import init_notebook_mode init_notebook_mode() # No need for connected=True anymore
2. Clean Up Conflicting Imports
Your code includes both plotly.plotly (for Plotly's online service) and offline modules, which can cause unexpected conflicts. Since you're working on local visualization, remove the online import line entirely to avoid clashes:
# Remove this line: import plotly.plotly as py import plotly.graph_objs as go from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot init_notebook_mode()
3. Fix Jupyter Lab Compatibility (If You're Using Lab)
If you're running Jupyter Lab instead of the classic Notebook, you'll need extra extensions to render Plotly plots properly:
- First install ipywidgets:
pip install ipywidgets # Or use conda if you prefer: conda install ipywidgets - Then install the Plotly Lab extension:
jupyter labextension install jupyterlab-plotly
Restart Jupyter Lab after installing to apply the changes.
4. Test with a Minimal Working Example
Here's a full, tested geographic visualization snippet that should work in most cases—use it to verify your setup:
import plotly.graph_objs as go from plotly.offline import init_notebook_mode, iplot # Initialize notebook mode init_notebook_mode() # Create a sample US city marker plot fig = go.Figure(data=go.Scattergeo( lon=[-122.4194, -118.2437, -74.0060], lat=[37.7749, 34.0522, 40.7128], mode='markers', marker=dict(size=12, color='darkblue') )) fig.update_layout( title='US City Geographic Markers', geo=dict( scope='usa', showland=True, landcolor='rgb(243, 243, 243)' ) ) # Render the plot directly in the notebook iplot(fig)
5. Restart Your Jupyter Kernel
Sometimes the issue is just a stuck kernel. Try restarting it (click "Kernel" > "Restart" in the Jupyter menu) and running your code again from scratch—this often fixes odd environment glitches.
内容的提问来源于stack exchange,提问作者user11787825

