1. matplotlib入门

Matplotlib提供了两种方法来作图:状态接口和面向对象。

  1. # 状态接口是通过pyplot模块来实现的,matplotlib会追踪绘图环境的当前状态
  2. # 这种方法适合快速画一些简单的图,但是对于多图和多轴会不方便
  3. In[2]: x = [-3, 5, 7]
  4. y = [10, 2, 5]
  5. plt.figure(figsize=(15,3))
  6. plt.plot(x, y)
  7. plt.xlim(0, 10)
  8. plt.ylim(-3, 8)
  9. plt.xlabel('X Axis')
  10. plt.ylabel('Y axis')
  11. plt.title('Line Plot')
  12. plt.suptitle('Figure Title', size=20, y=1.03)
  13. Out[2]: Text(0.5,1.03,'Figure Title')

1. matplotlib入门 - 图1

  1. # 面向对象的方法更易懂,修改的是哪个对象非常清晰
  2. # 而且代码更加pythonic,与pandas的交互方式更相似
  3. In[3]: fig, ax = plt.subplots(figsize=(15,3))
  4. ax.plot(x, y)
  5. ax.set_xlim(0, 10)
  6. ax.set_ylim(-3, 8)
  7. ax.set_xlabel('X axis')
  8. ax.set_ylabel('Y axis')
  9. ax.set_title('Line Plot')
  10. fig.suptitle('Figure Title', size=20, y=1.03)
  11. Out[3]: Text(0.5,1.03,'Figure Title')

1. matplotlib入门 - 图2

  1. # 用subplots函数创建一个带有一个Axes的Figure
  2. In[4]: fig, ax = plt.subplots(nrows=1, ncols=1)

1. matplotlib入门 - 图3

  1. # 查看fig和ax的数据类型
  2. In[5]: type(fig)
  3. Out[5]: matplotlib.figure.Figure
  4. In[6]: type(ax)
  5. Out[6]: matplotlib.axes._subplots.AxesSubplot
  1. # 查询Figure的大小,并放大
  2. In[7]: fig.get_size_inches()
  3. Out[7]: array([ 6., 4.])
  4. In[8]: fig.set_size_inches(14, 4)
  5. fig
  6. Out[8]:

1. matplotlib入门 - 图4

  1. # axes属性可以获取Figure的所有Axes
  2. In[9]: fig.axes
  3. Out[9]: [<matplotlib.axes._subplots.AxesSubplot at 0x1134202b0>]
  1. # 判断Axes列表中的第一个元素和之前定义的ax是否相同
  2. In[10]: fig.axes[0] is ax
  3. Out[10]: True
  1. # 用浮点数显示不同的灰度
  2. In[11]: fig.set_facecolor('.9')
  3. ax.set_facecolor('.7')
  4. fig
  5. Out[11]:

1. matplotlib入门 - 图5

  1. # 检查Axes的子元素,每个基本的图都有四个spine和两个axis
  2. # spine是数据边界,即四条边
  3. # x和y轴对象包含了更多的绘图对象,比如刻度、标签
  4. In[12]: ax_children = ax.get_children()
  5. ax_children
  6. Out[12]: [<matplotlib.spines.Spine at 0x11145b358>,
  7. <matplotlib.spines.Spine at 0x11145b0f0>,
  8. <matplotlib.spines.Spine at 0x11145ae80>,
  9. <matplotlib.spines.Spine at 0x11145ac50>,
  10. <matplotlib.axis.XAxis at 0x11145aa90>,
  11. <matplotlib.axis.YAxis at 0x110fa8d30>,
  12. ...]
  1. # 通过spines属性直接访问spines
  2. >>> spines = ax.spines
  3. >>> spines
  4. OrderedDict([('left', <matplotlib.spines.Spine at 0x11279e320>),
  5. ('right', <matplotlib.spines.Spine at 0x11279e0b8>),
  6. ('bottom', <matplotlib.spines.Spine at 0x11279e048>),
  7. ('top', <matplotlib.spines.Spine at 0x1127eb5c0>)])
  1. # 选中左边,改变它的位置和宽度,使底边不可见
  2. In[13]: spine_left = spines['left']
  3. spine_left.set_position(('outward', -100))
  4. spine_left.set_linewidth(5)
  5. spine_bottom = spines['bottom']
  6. spine_bottom.set_visible(False)
  7. fig
  8. Out[13]:

1. matplotlib入门 - 图6

  1. # 通过属性xaxis和yaxis可以修改属性,有些属性也可以通过Axes对象直接修改
  2. In[14]: ax.xaxis.grid(True, which='major', linewidth=2, color='black', linestyle='--')
  3. ax.xaxis.set_ticks([.2, .4, .55, .93])
  4. ax.xaxis.set_label_text('X Axis', family='Verdana', fontsize=15)
  5. ax.set_ylabel('Y Axis', family='Calibri', fontsize=20)
  6. ax.set_yticks([.1, .9])
  7. ax.set_yticklabels(['point 1', 'point 9'], rotation=45)
  8. fig
  9. Out[14]:

1. matplotlib入门 - 图7

原理

  1. # plt.subplots函数返回的是一个元组
  2. In[22]: plot_objects = plt.subplots()
  3. In[23]: type(plot_objects)
  4. Out[23]: tuple
  5. In[24]: fig = plot_objects[0]
  6. ax = plot_objects[1]
  1. # 如果创建了多个轴,则元组的第二个元素是一个包含所有轴的NumPy数组
  2. In[25]: plot_objects = plt.subplots(2, 4, figsize=(14, 4))

1. matplotlib入门 - 图8

  1. In[26]: plot_objects[1]
  2. Out[26]: array([[<matplotlib.axes._subplots.AxesSubplot object at 0x113eefa20>,
  3. <matplotlib.axes._subplots.AxesSubplot object at 0x113f7ccc0>,
  4. <matplotlib.axes._subplots.AxesSubplot object at 0x11413ed68>,
  5. <matplotlib.axes._subplots.AxesSubplot object at 0x114213e48>],
  6. [<matplotlib.axes._subplots.AxesSubplot object at 0x11424ce80>,
  7. <matplotlib.axes._subplots.AxesSubplot object at 0x1142807b8>,
  8. <matplotlib.axes._subplots.AxesSubplot object at 0x1142b8898>,
  9. <matplotlib.axes._subplots.AxesSubplot object at 0x1142f2898>]], dtype=object)
  1. # 一些属性和与其等价的get方法
  2. In[27]: fig.get_axes() == fig.axes
  3. Out[27]: True
  4. In[29]: fig.axes == fig.get_axes()
  5. Out[29]: True
  6. In[30]: ax.xaxis == ax.get_xaxis()
  7. Out[30]: True
  8. In[31]: ax.yaxis == ax.get_yaxis()
  9. Out[31]: True

更多

  1. # 查询xaxis的所有属性
  2. In[15]: ax.xaxis.properties()
  3. Out[15]:
  4. {'agg_filter': None,
  5. 'alpha': None,
  6. 'animated': False,
  7. 'children': [Text(0.5,22.2,'X Axis'),
  8. Text(1,23.2,''),
  9. <matplotlib.axis.XTick at 0x113371fd0>,
  10. <matplotlib.axis.XTick at 0x113514240>,
  11. <matplotlib.axis.XTick at 0x1136387b8>,
  12. <matplotlib.axis.XTick at 0x113638f60>],
  13. 'clip_box': TransformedBbox(Bbox([[0.0, 0.0], [1.0, 1.0]]), CompositeGenericTransform(CompositeGenericTransform(BboxTransformTo(Bbox([[0.0, 0.0], [1.0, 1.0]])), Affine2D(array([[ 1., 0., 0.],
  14. [ 0., 1., 0.],
  15. [ 0., 0., 1.]]))), BboxTransformTo(TransformedBbox(Bbox([[0.125, 0.125], [0.9, 0.88]]), BboxTransformTo(TransformedBbox(Bbox([[0.0, 0.0], [14.0, 4.0]]), Affine2D(array([[ 72., 0., 0.],
  16. [ 0., 72., 0.],
  17. [ 0., 0., 1.]])))))))),
  18. 'clip_on': True,
  19. 'clip_path': None,
  20. 'contains': None,
  21. 'data_interval': array([ inf, -inf]),
  22. 'figure': <matplotlib.figure.Figure at 0x11332abe0>,
  23. 'gid': None,
  24. 'gridlines': <a list of 4 Line2D gridline objects>,
  25. 'label': Text(0.5,22.2,'X Axis'),
  26. 'label_position': 'bottom',
  27. 'label_text': 'X Axis',
  28. 'major_formatter': <matplotlib.ticker.ScalarFormatter at 0x113543780>,
  29. 'major_locator': <matplotlib.ticker.FixedLocator at 0x113648ba8>,
  30. 'major_ticks': [<matplotlib.axis.XTick at 0x113371fd0>,
  31. <matplotlib.axis.XTick at 0x113514240>,
  32. <matplotlib.axis.XTick at 0x1136387b8>,
  33. <matplotlib.axis.XTick at 0x113638f60>],
  34. 'majorticklabels': <a list of 4 Text major ticklabel objects>,
  35. 'majorticklines': <a list of 8 Line2D ticklines objects>,
  36. 'majorticklocs': array([ 0.2 , 0.4 , 0.55, 0.93]),
  37. 'minor_formatter': <matplotlib.ticker.NullFormatter at 0x11341a518>,
  38. 'minor_locator': <matplotlib.ticker.NullLocator at 0x113624198>,
  39. 'minor_ticks': [],
  40. 'minorticklabels': <a list of 0 Text minor ticklabel objects>,
  41. 'minorticklines': <a list of 0 Line2D ticklines objects>,
  42. 'minorticklocs': [],
  43. 'minpos': inf,
  44. 'offset_text': Text(1,23.2,''),
  45. 'path_effects': [],
  46. 'picker': None,
  47. 'pickradius': 15,
  48. 'rasterized': None,
  49. 'scale': 'linear',
  50. 'sketch_params': None,
  51. 'smart_bounds': False,
  52. 'snap': None,
  53. 'tick_padding': 3.5,
  54. 'tick_space': 26,
  55. 'ticklabels': <a list of 4 Text major ticklabel objects>,
  56. 'ticklines': <a list of 8 Line2D ticklines objects>,
  57. 'ticklocs': array([ 0.2 , 0.4 , 0.55, 0.93]),
  58. 'ticks_direction': array(['out', 'out', 'out', 'out'],
  59. dtype='<U3'),
  60. 'ticks_position': 'bottom',
  61. 'transform': IdentityTransform(),
  62. 'transformed_clip_path_and_affine': (None, None),
  63. 'units': None,
  64. 'url': None,
  65. 'view_interval': array([ 0., 1.]),
  66. 'visible': True,
  67. 'zorder': 1.5}