修复matplotlib'未安装为框架'错误w/out更改$ HOME中的.matplotlib配置

Zac*_*nta 2 python macos matplotlib virtualenv tensorflow

上下文

  • 机器:64位Mac
  • 操作系统:macOS 10.10.5

错误消息

以下课程[ Jerry Kurata 'Tensorflow: Getting Started']运行以下内容:

import tensorflow as tf
import numpy as np
import math
import matplotlib.pyplot as plt
import matplotlib.animation as animation

num_house = 160
np.random.seed(42)
house_size = np.random.randint(low=1000, high=3500, size=num_house)

np.random.seed(42)
house_price = house_size * 100.0 + np.random.randint(low=20000, high=70000, size=num_house)

plt.plot(house_size, house_price, "bx")
plt.xlabel("price")
plt.ylabel("size")
plt.show
Run Code Online (Sandbox Code Playgroud)

收到此错误

**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.

试图解决

  • 已经咨询了这个答案[ /sf/answers/1525293591/],但关注的是以一种会影响此虚拟环境之外的其他项目的方式更改与全局matplotlib设置相关的任何内容

Zac*_*nta 11

请参阅上面的答案使用matplotlib Python安装问题并参考其中一条注释:

有些用户可能不想更改所有脚本的后端.这个页面 - matplotlib.org/faq/usage_faq.html#what-is-a-backend - 告诉另一种方式:在此之后将语句import matplotlib包含为mpl然后mpl.use('TkAgg'),然后执行导入pyplot.

并在导入中设置matplotlib后端,就像这样

import tensorflow as tf
import numpy as np
import math

## SET BACKEND
import matplotlib as mpl
mpl.use('TkAgg')

import matplotlib.pyplot as plt
import matplotlib.animation as animation

num_house = 160
np.random.seed(42)
house_size = np.random.randint(low=1000, high=3500, size=num_house)

np.random.seed(42)
house_price = house_size * 100.0 + np.random.randint(low=20000, high=70000, size=num_house)

plt.plot(house_size, house_price, "bx")
plt.xlabel("price")
plt.ylabel("size")
plt.show
Run Code Online (Sandbox Code Playgroud)

这样,你就不需要在$ HOME中触摸matplotlib了