由于想在Rstudio中做EEG相关分析,安装了anaconda并在Rstudio全局选项中选择了创建的虚拟环境。
library("reticulate")
后在执行Python示例代码:
import numpy as np
import mne
sample_data_raw_file = ('./sample_data/MEG/sample/sample_audvis_filt-0-40_raw.fif') #导入数据√
raw = mne.io.read_raw_fif(sample_data_raw_file) #导入数据√
raw.plot_psd(fmax=50) #报错行. 原本应该输出一张交互式图像
#J:\Anaconda\envs\mne\lib\site-packages\mne\viz\utils.py:137: UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure. (fig or plt).show(**kwargs)
查找资料是要修改matplotlib的后端为qt5agg。故做以下尝试:
import numpy as np
import mne
import matplotlib
matplotlib.use('Qt5Agg')
sample_data_raw_file = ('./sample_data/MEG/sample/sample_audvis_filt-0-40_raw.fif')
raw = mne.io.read_raw_fif(sample_data_raw_file)
raw.plot_psd(fmax=50)
运行以上代码跳出了交互式窗口但是是黑屏而且Rstudio直接崩溃了(R session Aborted)。
于是 我用Jupyter notebook 运行相同的示例代码,发现里面开头有多一行% matplotlib inline
,但是同样会报错而且没有交互页面:
UserWarning: Matplotlib is currently using module://matplotlib_inline.backend_inline, which is a non-GUI backend, so cannot show the figure.
(fig or plt).show(**kwargs)
用相同的修改方式修改matplotlib的后端为qt5agg就可以正常跳出交互页面,报错也消失了。
在Jupyter notebook中如果不使用matplotlib.use(qt5agg)
而是把% matplotlib inline
改为% matplotlib qt
也可以正常出图。
所以这是Rstudio的问题吗。希望有大佬可帮忙看下,感谢。
> sessionInfo()
R version 4.2.2 (2022-10-31 ucrt)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 22621)
Matrix products: default
locale:
[1] LC_COLLATE=Chinese (Simplified)_China.utf8
[2] LC_CTYPE=Chinese (Simplified)_China.utf8
[3] LC_MONETARY=Chinese (Simplified)_China.utf8
[4] LC_NUMERIC=C
[5] LC_TIME=Chinese (Simplified)_China.utf8
attached base packages:
[1] stats graphics grDevices utils datasets methods base
loaded via a namespace (and not attached):
[1] Rcpp_1.0.9 lattice_0.20-45 here_1.0.1 png_0.1-8
[5] digest_0.6.31 rprojroot_2.0.3 grid_4.2.2 jsonlite_1.8.4
[9] evaluate_0.19 rlang_1.0.6 cli_3.5.0 rstudioapi_0.14
[13] Matrix_1.5-1 reticulate_1.26 rmarkdown_2.19 tools_4.2.2
[17] yaml_2.3.6 xfun_0.36 fastmap_1.1.0 compiler_4.2.2
[21] htmltools_0.5.4 knitr_1.41
python虚拟环境信息:
>>> mne.sys_info()
Platform: Windows-10-10.0.22621-SP0
Python: 3.10.8 | packaged by conda-forge | (main, Nov 22 2022, 08:16:33) [MSC v.1929 64 bit (AMD64)]
Executable: J:/Anaconda/envs/mne/python.exe
CPU: Intel64 Family 6 Model 140 Stepping 1, GenuineIntel: 8 cores
Memory: 15.7 GB
mne: 1.3.0
numpy: 1.23.5 {unknown linalg bindings}
scipy: 1.10.0
matplotlib: 3.6.2 {backend=agg}
sklearn: 1.2.0
numba: 0.56.4
nibabel: 4.0.2
nilearn: 0.10.0
dipy: 1.5.0
openmeeg: Not found
cupy: Not found
pandas: 1.5.2
pyvista: 0.37.0