Fork me on GitHub

  matplotlib 是python最著名的2D绘图库,它提供了一整套和matlab相似的命令API,十分适合交互式地进行制图。而且也可以方便地将它作为绘图控件,嵌入GUI应用程序中。通过简单的绘图语句,就可以绘制出高质量的图了。

这里我们就主要讲一下inshow()函数的使用。

  首先看一下怎么基本画图的流程:

 1 import matplotlib.pyplot as plt 
 2 
 3 #创建新的figure
 4 fig = plt.figure()
 5 
 6 #必须通过add_subplot()创建一个或多个绘图
 7 ax = fig.add_subplot(221)
 8 
 9 #绘制2x2两行两列共四个图,编号从1开始
10 ax1 = fig.add_subplot(221)
11 ax2 = fig.add_subplot(222)
12 ax3 = fig.add_subplot(223)
13 ax4 = fig.add_subplot(224)
14 
15 #图片的显示
16 plt.show()

  截图如下所示:

  

  热图(heatmap)是数据分析的常用方法,通过色差、亮度来展示数据的差异、易于理解。Python在Matplotlib库中,调用imshow()函数实现热图绘制。

 1 #coding=utf-8
 2 import matplotlib.pyplot as plt 
 3 import numpy as np
 4 
 5 points = np.arange(-5,5,0.01)
 6 
 7 xs,ys = np.meshgrid(points,points)
 8 
 9 z = np.sqrt(xs**2 + ys**2)
10 
11 #创建新的figure
12 fig = plt.figure()
13 
14 #绘制2x2两行两列共四个图,编号从1开始
15 ax = fig.add_subplot(221)
16 ax.imshow(z)
17 
18 ax = fig.add_subplot(222)
19 #使用自定义的colormap(灰度图)
20 ax.imshow(z,cmap=plt.cm.gray)
21 
22 ax = fig.add_subplot(223)
23 #使用自定义的colormap
24 ax.imshow(z,cmap=plt.cm.cool)
25 
26 ax = fig.add_subplot(224)
27 #使用自定义的colormap
28 ax.imshow(z,cmap=plt.cm.hot)
29 
30 #图片的显示
31 plt.show()

 

 输出结果:

 

  错误备忘:

问题一: NameError: name 'imshow' is not defined

解决方案:在文件中添加,

from pylab import *

 

问题二:ImportError: No module named _internal

解决方案:原因是安装好pip 后续又安装了pip,导致版本冲突。

解决方法:

后续又安装了pip,导致版本冲突。

解决方法:

sudo apt remove python-pip

 

posted on 2018-11-21 11:27  虚生  阅读(56201)  评论(0编辑  收藏  举报