matplotlib的绘图在命令行中不显示的问题

作者 happyWang 日期 2018-06-01 Views
matplotlib的绘图在命令行中不显示的问题

最近在看Google的机器学习速成课程MLCC

中午的时候在看关于pandas这个数据分析库的介绍

中间有一个用直方图显示数据集的代码:

import pandas as pd
california_housing_dataframe = pd.read_csv("https://storage.googleapis.com/mledu-datasets/california_housing_train.csv", sep=",")
california_housing_dataframe.hist('housing_median_age')

在这个介绍里面可以执行代码显示出好看的直方图出来。

我这边想本地也能执行出这样的效果,就依次安装了pandasmatplotlib,然后执行上述代码

结果只返回了一句:

array([[<matplotlib.axes._subplots.AxesSubplot object at 0x1072c14e0>]], dtype=object)

按照matplotlib官网对于macosx下图形不显示的一个修复指南折腾了一个下午,还是不显示

最后偶然在stackoverflow上看到一个方案

在代码前方加上matplotlib.pyplot的引用:

import matplotlib.pyplot as plt

再在执行hist完成之后加上:

plt.show()

最终执行,就会新出一个图形弹窗显示直方图:

同时底下也有人对这个情况做出了解释:

Inside a GUI such as an IPython notebook, you may not need to call plt.show() depending on how the GUI is configured. If you run the Python script from the command line, then you would have to call plt.show()

有一些GUI的环境里面执行,会自动的去展示相关的结果,但是在命令行里面,就需要手动的调用plt.show()