Matplotlib 基础¶

在使用Numpy之前,需要了解一些画图的基础。

Matplotlib是一个类似Matlab的工具包,主页地址为

http://matplotlib.org

导入 matplotlibnumpy

In [1]:

  1. %pylab
  1. Using matplotlib backend: Qt4Agg
  2. Populating the interactive namespace from numpy and matplotlib

plot 二维图¶

  1. plot(y)
  2. plot(x, y)
  3. plot(x, y, format_string)

只给定 y 值,默认以下标为 x 轴:

In [2]:

  1. %matplotlib inline
  2. x = linspace(0, 2 * pi, 50)
  3. plot(sin(x))

Out[2]:

  1. [<matplotlib.lines.Line2D at 0xa086fd0>]

03.02 Matplotlib 基础 - 图1

给定 xy 值:

In [3]:

  1. plot(x, sin(x))

Out[3]:

  1. [<matplotlib.lines.Line2D at 0xa241898>]

03.02 Matplotlib 基础 - 图2

多条数据线:

In [4]:

  1. plot(x, sin(x),
  2. x, sin(2 * x))

Out[4]:

  1. [<matplotlib.lines.Line2D at 0xa508b00>,
  2. <matplotlib.lines.Line2D at 0xa508d30>]

03.02 Matplotlib 基础 - 图3

使用字符串,给定线条参数:

In [5]:

  1. plot(x, sin(x), 'r-^')

Out[5]:

  1. [<matplotlib.lines.Line2D at 0xba6ea20>]

03.02 Matplotlib 基础 - 图4

多线条:

In [9]:

  1. plot(x, sin(x), 'b-o',
  2. x, sin(2 * x), 'r-^')

Out[9]:

  1. [<matplotlib.lines.Line2D at 0xbcf1710>,
  2. <matplotlib.lines.Line2D at 0xbcf1940>]

03.02 Matplotlib 基础 - 图5

更多参数设置,请查阅帮助。事实上,字符串使用的格式与Matlab相同。

scatter 散点图¶

  1. scatter(x, y)
  2. scatter(x, y, size)
  3. scatter(x, y, size, color)

假设我们想画二维散点图:

In [10]:

  1. plot(x, sin(x), 'bo')

Out[10]:

  1. [<matplotlib.lines.Line2D at 0xbd6c0b8>]

03.02 Matplotlib 基础 - 图6

可以使用 scatter 达到同样的效果:

In [11]:

  1. scatter(x, sin(x))

Out[11]:

  1. <matplotlib.collections.PathCollection at 0xbd996d8>

03.02 Matplotlib 基础 - 图7

事实上,scatter函数与Matlab的用法相同,还可以指定它的大小,颜色等参数:

In [12]:

  1. x = rand(200)
  2. y = rand(200)
  3. size = rand(200) * 30
  4. color = rand(200)
  5. scatter(x, y, size, color)
  6. # 显示颜色条
  7. colorbar()

Out[12]:

  1. <matplotlib.colorbar.Colorbar instance at 0x000000000C31F448>

03.02 Matplotlib 基础 - 图8

多图¶

使用figure()命令产生新的图像:

In [13]:

  1. t = linspace(0, 2*pi, 50)
  2. x = sin(t)
  3. y = cos(t)
  4. figure()
  5. plot(x)
  6. figure()
  7. plot(y)

Out[13]:

  1. [<matplotlib.lines.Line2D at 0xc680cf8>]

03.02 Matplotlib 基础 - 图9

03.02 Matplotlib 基础 - 图10

或者使用 subplot 在一幅图中画多幅子图:

  1. subplot(row, column, index)

In [15]:

  1. subplot(1, 2, 1)
  2. plot(x)
  3. subplot(1, 2, 2)
  4. plot(y)

Out[15]:

  1. [<matplotlib.lines.Line2D at 0xcd47518>]

03.02 Matplotlib 基础 - 图11

向图中添加数据¶

默认多次 plot 会叠加:

In [16]:

  1. plot(x)
  2. plot(y)

Out[16]:

  1. [<matplotlib.lines.Line2D at 0xcbcfd30>]

03.02 Matplotlib 基础 - 图12

可以跟Matlab类似用 hold(False)关掉,这样新图会将原图覆盖:

In [17]:

  1. plot(x)
  2. hold(False)
  3. plot(y)
  4. # 恢复原来设定
  5. hold(True)

Out[17]:

  1. [<matplotlib.lines.Line2D at 0xcf4b9b0>]

03.02 Matplotlib 基础 - 图13

标签¶

可以在 plot 中加入 label ,使用 legend 加上图例:

In [19]:

  1. plot(x, label='sin')
  2. plot(y, label='cos')
  3. legend()

Out[19]:

  1. <matplotlib.legend.Legend at 0xd2089b0>

03.02 Matplotlib 基础 - 图14

或者直接在 legend中加入:

In [21]:

  1. plot(x)
  2. plot(y)
  3. legend(['sin', 'cos'])

Out[21]:

  1. <matplotlib.legend.Legend at 0xd51fb00>

03.02 Matplotlib 基础 - 图15

坐标轴,标题,网格¶

可以设置坐标轴的标签和标题:

In [22]:

  1. plot(x, sin(x))
  2. xlabel('radians')
  3. # 可以设置字体大小
  4. ylabel('amplitude', fontsize='large')
  5. title('Sin(x)')

Out[22]:

  1. <matplotlib.text.Text at 0xd727dd8>

03.02 Matplotlib 基础 - 图16

用 'grid()' 来显示网格:

In [23]:

  1. plot(x, sin(x))
  2. xlabel('radians')
  3. ylabel('amplitude', fontsize='large')
  4. title('Sin(x)')
  5. grid()

03.02 Matplotlib 基础 - 图17

清除、关闭图像¶

清除已有的图像使用:

  1. clf()

关闭当前图像:

  1. close()

关闭所有图像:

  1. close('all')

imshow 显示图片¶

灰度图片可以看成二维数组:

In [25]:

  1. # 导入lena图片
  2. from scipy.misc import lena
  3. img = lena()
  4. img

Out[25]:

  1. array([[162, 162, 162, ..., 170, 155, 128],
  2. [162, 162, 162, ..., 170, 155, 128],
  3. [162, 162, 162, ..., 170, 155, 128],
  4. ...,
  5. [ 43, 43, 50, ..., 104, 100, 98],
  6. [ 44, 44, 55, ..., 104, 105, 108],
  7. [ 44, 44, 55, ..., 104, 105, 108]])

我们可以用 imshow() 来显示图片数据:

In [26]:

  1. imshow(img,
  2. # 设置坐标范围
  3. extent = [-25, 25, -25, 25],
  4. # 设置colormap
  5. cmap = cm.bone)
  6. colorbar()

Out[26]:

  1. <matplotlib.colorbar.Colorbar instance at 0x000000000DECFD88>

03.02 Matplotlib 基础 - 图18

更多参数和用法可以参阅帮助。

这里 cm 表示 colormap,可以看它的种类:

In [28]:

  1. dir(cm)

Out[28]:

  1. [u'Accent',
  2. u'Accent_r',
  3. u'Blues',
  4. u'Blues_r',
  5. u'BrBG',
  6. u'BrBG_r',
  7. u'BuGn',
  8. u'BuGn_r',
  9. u'BuPu',
  10. u'BuPu_r',
  11. u'CMRmap',
  12. u'CMRmap_r',
  13. u'Dark2',
  14. u'Dark2_r',
  15. u'GnBu',
  16. u'GnBu_r',
  17. u'Greens',
  18. u'Greens_r',
  19. u'Greys',
  20. u'Greys_r',
  21. 'LUTSIZE',
  22. u'OrRd',
  23. u'OrRd_r',
  24. u'Oranges',
  25. u'Oranges_r',
  26. u'PRGn',
  27. u'PRGn_r',
  28. u'Paired',
  29. u'Paired_r',
  30. u'Pastel1',
  31. u'Pastel1_r',
  32. u'Pastel2',
  33. u'Pastel2_r',
  34. u'PiYG',
  35. u'PiYG_r',
  36. u'PuBu',
  37. u'PuBuGn',
  38. u'PuBuGn_r',
  39. u'PuBu_r',
  40. u'PuOr',
  41. u'PuOr_r',
  42. u'PuRd',
  43. u'PuRd_r',
  44. u'Purples',
  45. u'Purples_r',
  46. u'RdBu',
  47. u'RdBu_r',
  48. u'RdGy',
  49. u'RdGy_r',
  50. u'RdPu',
  51. u'RdPu_r',
  52. u'RdYlBu',
  53. u'RdYlBu_r',
  54. u'RdYlGn',
  55. u'RdYlGn_r',
  56. u'Reds',
  57. u'Reds_r',
  58. 'ScalarMappable',
  59. u'Set1',
  60. u'Set1_r',
  61. u'Set2',
  62. u'Set2_r',
  63. u'Set3',
  64. u'Set3_r',
  65. u'Spectral',
  66. u'Spectral_r',
  67. u'Wistia',
  68. u'Wistia_r',
  69. u'YlGn',
  70. u'YlGnBu',
  71. u'YlGnBu_r',
  72. u'YlGn_r',
  73. u'YlOrBr',
  74. u'YlOrBr_r',
  75. u'YlOrRd',
  76. u'YlOrRd_r',
  77. '__builtins__',
  78. '__doc__',
  79. '__file__',
  80. '__name__',
  81. '__package__',
  82. '_generate_cmap',
  83. '_reverse_cmap_spec',
  84. '_reverser',
  85. 'absolute_import',
  86. u'afmhot',
  87. u'afmhot_r',
  88. u'autumn',
  89. u'autumn_r',
  90. u'binary',
  91. u'binary_r',
  92. u'bone',
  93. u'bone_r',
  94. u'brg',
  95. u'brg_r',
  96. u'bwr',
  97. u'bwr_r',
  98. 'cbook',
  99. 'cmap_d',
  100. 'cmapname',
  101. 'colors',
  102. u'cool',
  103. u'cool_r',
  104. u'coolwarm',
  105. u'coolwarm_r',
  106. u'copper',
  107. u'copper_r',
  108. 'cubehelix',
  109. u'cubehelix_r',
  110. 'datad',
  111. 'division',
  112. u'flag',
  113. u'flag_r',
  114. 'get_cmap',
  115. u'gist_earth',
  116. u'gist_earth_r',
  117. u'gist_gray',
  118. u'gist_gray_r',
  119. u'gist_heat',
  120. u'gist_heat_r',
  121. u'gist_ncar',
  122. u'gist_ncar_r',
  123. u'gist_rainbow',
  124. u'gist_rainbow_r',
  125. u'gist_stern',
  126. u'gist_stern_r',
  127. u'gist_yarg',
  128. u'gist_yarg_r',
  129. u'gnuplot',
  130. u'gnuplot2',
  131. u'gnuplot2_r',
  132. u'gnuplot_r',
  133. u'gray',
  134. u'gray_r',
  135. u'hot',
  136. u'hot_r',
  137. u'hsv',
  138. u'hsv_r',
  139. u'jet',
  140. u'jet_r',
  141. 'ma',
  142. 'mpl',
  143. u'nipy_spectral',
  144. u'nipy_spectral_r',
  145. 'np',
  146. u'ocean',
  147. u'ocean_r',
  148. 'os',
  149. u'pink',
  150. u'pink_r',
  151. 'print_function',
  152. u'prism',
  153. u'prism_r',
  154. u'rainbow',
  155. u'rainbow_r',
  156. 'register_cmap',
  157. 'revcmap',
  158. u'seismic',
  159. u'seismic_r',
  160. 'six',
  161. 'spec',
  162. 'spec_reversed',
  163. u'spectral',
  164. u'spectral_r',
  165. u'spring',
  166. u'spring_r',
  167. u'summer',
  168. u'summer_r',
  169. u'terrain',
  170. u'terrain_r',
  171. 'unicode_literals',
  172. u'winter',
  173. u'winter_r']

使用不同的 colormap 会有不同的显示效果。

In [29]:

  1. imshow(img, cmap=cm.RdGy_r)

Out[29]:

  1. <matplotlib.image.AxesImage at 0xe0883c8>

03.02 Matplotlib 基础 - 图19

从脚本中运行¶

在脚本中使用 plot 时,通常图像是不会直接显示的,需要增加 show() 选项,只有在遇到 show() 命令之后,图像才会显示。

直方图¶

从高斯分布随机生成1000个点得到的直方图:

In [30]:

  1. hist(randn(1000))

Out[30]:

  1. (array([ 2., 7., 37., 119., 216., 270., 223., 82., 31., 13.]),
  2. array([-3.65594649, -2.98847032, -2.32099415, -1.65351798, -0.98604181,
  3. -0.31856564, 0.34891053, 1.0163867 , 1.68386287, 2.35133904,
  4. 3.01881521]),
  5. <a list of 10 Patch objects>)

03.02 Matplotlib 基础 - 图20

更多例子请参考下列网站:

http://matplotlib.org/gallery.html

原文: https://nbviewer.jupyter.org/github/lijin-THU/notes-python/blob/master/03-numpy/03.02-matplotlib-basics.ipynb