Mac中使用pycharm引包matplotlib失败

时间:2024-08-19 12:04:38

最开始是使用matplotlib这个包,然后在pycharm中失败,然后在终端中pip install matplotlib,发现,安装了以后,pycharm依然找不到包。

代码如下:

import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt num_points = 1000 vectors_set = []
for i in range(num_points):
x1 = np.random.normal(0.0, 0.55)
y1 = x1 * 0.1 + 0.3 + np.random.normal(0.0, 0.03)
vectors_set.append([x1, y1]) x_data = [v[0] for v in vectors_set]
y_data = [v[1] for v in vectors_set] plt.scatter(x_data,y_data,c='r')
plt.show()

步骤1:查看pycharm中的python解释器是否正确

Mac中使用pycharm引包matplotlib失败

Mac中使用pycharm引包matplotlib失败

/anaconda3/envs/tensorflow/bin/python3.6 /Users/tanchao/Documents/pythonwork/tensorflow/test.py,正确

步骤2:查看终端中的python是哪一个

使用命令:

which python

返回结果:

Mac中使用pycharm引包matplotlib失败

说明终端默认的python解释器和pycharm中的不一致。

步骤3:修改终端默认的python解释器

在终端中输入

open ~/.bash_profile

写入:

export PATH=${PATH}:/Library/Frameworks/Python.framework/Versions/3.6/bin

重命名python(不知道该步骤是否有必要)

alias python="/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6"

然后终端中输入:

source ~/.bash_profile

步骤4:再次检查python版本

在终端中输入:

which python

查看是否成功。

Mac中使用pycharm引包matplotlib失败

发现此时终端的python解释器和pycharm的解释器一致。

步骤5:重启pycharm

发现还有错。

类似于这样的错误

from matplotlib.backends import _macosx
RuntimeError: Python is not installed as a framework. The Mac OS X backend will not be able to function correctly if Python is not installed as a framework. See the Python documentation for more information on installing Python as a framework on Mac OS X. Please either reinstall Python as a framework, or try one of the other backends. If you are Working with Matplotlib in a virtual enviroment see 'Working with Matplotlib in Virtual environments' in the Matplotlib FAQ

步骤6:修改配置文件

在终端中输入

vim ~/.matplotlib/matplotlibrc

在文件中输入:

backend: TkAgg

步骤7:重启pycharm

发现可以运行。

Mac中使用pycharm引包matplotlib失败