NameError: name 'save_fig' is not defined

NameError: name 'save_fig' is not defined

import matplotlib.pyplot as plt
save_fig("attribute_histogram_plots")
  • 编译错误,NameError: name ‘save_fig’ is not defined,如图:
    NameError: name 'save_fig' is not defined
/usr/local/bin/python3.6 /Users/zhangzhenkai/Documents/ScikitLearn/ch1/sec2/LoadData.py
Traceback (most recent call last):
  File "/Users/zhangzhenkai/Documents/ScikitLearn/ch1/sec2/LoadData.py", line 22, in <module>
    save_fig("attribute_histogram_plots")
NameError: name 'save_fig' is not defined

Process finished with exit code 1
  • 解决方法,将程序修改为:
import matplotlib.pyplot as plt
plt.savefig("attribute_histogram_plots")
  • 或者,定义一个save_fig函数:
housing_path = HOUSING_PATH      # 设置路径
def save_fig(fig_id, tight_layout=True):
    path = os.path.join(housing_path, "images", fig_id + ".png")
    print("Saving figure", fig_id)
    if tight_layout:
        plt.tight_layout()
    plt.savefig(path, format='png', dpi=300)
  • 调用函数虽然可以保存图片,但是程序运行耗费的时间很长,建议采用第一种方法。