尝试解决使用jupyter绘图无法交互的问题
问题描述
在练习《python数据手册》中matplotlib部分时,书中提到的魔术方法
// 在notebook中启动交互式图形
% matplotlib notebook
无法使用并报错,以下是尝试解决的步骤,在此记录以防忘记。
一、升级jupyter lab
首先,我在conda中的jupyter notebook版本为6.1.4,但是jupyter lab版本只有1.2.6,而lab的许多拓展必须在2以上的版本才能使用,必须首先升级lab的版本,使用
conda update jupyterlab
升级发现报错“PackageNotInstalledError: Package is not installed in prefix.”但是,相同方法升级notebook就没有任何问题,可能是版本实在太低,于是使用
pip install --upgrade jupyterlab
完成lab的升级
二、安装jupyterlab拓展
由于使用交互绘图模式报错“Javascript Error: IPython is not defined”,查询错误原因,知道可以在conda中使用如下命令解决:
[原文链接: link.]
conda install -c conda-forge ipympl
# If using JupyterLab
conda install nodejs
jupyter labextension install @jupyter-widgets/jupyterlab-manager
jupyter lab build
# Later, if updating a previous Lab install:
conda install ipympl
jupyter lab build
其中,jupyter labextension install 命令还遇到了WinError5的权限问题,右键管理员权限运行anaconda powershell prompt即可解决。
随后发现必须按照链接原文评论区中所说,补充一条命令以激活拓展:
jupyter nbextension enable --py widgetsnbextension
重启jupyter,此时交互式绘图模式已经可以正常使用,不论使用%maytplotlib notebook
还是 %matplotlib widget
均可以进入交互式绘图模式。效果如下图所示,笔者可以旋转图中莫比乌斯带的3d图像,而在inline模式下3d图的查看是非常不便的: