1. matplotlib入门
Matplotlib提供了两种方法来作图:状态接口和面向对象。
# 状态接口是通过pyplot模块来实现的,matplotlib会追踪绘图环境的当前状态
# 这种方法适合快速画一些简单的图,但是对于多图和多轴会不方便
In[2]: x = [-3, 5, 7]
y = [10, 2, 5]
plt.figure(figsize=(15,3))
plt.plot(x, y)
plt.xlim(0, 10)
plt.ylim(-3, 8)
plt.xlabel('X Axis')
plt.ylabel('Y axis')
plt.title('Line Plot')
plt.suptitle('Figure Title', size=20, y=1.03)
Out[2]: Text(0.5,1.03,'Figure Title')
# 面向对象的方法更易懂,修改的是哪个对象非常清晰
# 而且代码更加pythonic,与pandas的交互方式更相似
In[3]: fig, ax = plt.subplots(figsize=(15,3))
ax.plot(x, y)
ax.set_xlim(0, 10)
ax.set_ylim(-3, 8)
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_title('Line Plot')
fig.suptitle('Figure Title', size=20, y=1.03)
Out[3]: Text(0.5,1.03,'Figure Title')
# 用subplots函数创建一个带有一个Axes的Figure
In[4]: fig, ax = plt.subplots(nrows=1, ncols=1)
# 查看fig和ax的数据类型
In[5]: type(fig)
Out[5]: matplotlib.figure.Figure
In[6]: type(ax)
Out[6]: matplotlib.axes._subplots.AxesSubplot
# 查询Figure的大小,并放大
In[7]: fig.get_size_inches()
Out[7]: array([ 6., 4.])
In[8]: fig.set_size_inches(14, 4)
fig
Out[8]:
# axes属性可以获取Figure的所有Axes
In[9]: fig.axes
Out[9]: [<matplotlib.axes._subplots.AxesSubplot at 0x1134202b0>]
# 判断Axes列表中的第一个元素和之前定义的ax是否相同
In[10]: fig.axes[0] is ax
Out[10]: True
# 用浮点数显示不同的灰度
In[11]: fig.set_facecolor('.9')
ax.set_facecolor('.7')
fig
Out[11]:
# 检查Axes的子元素,每个基本的图都有四个spine和两个axis
# spine是数据边界,即四条边
# x和y轴对象包含了更多的绘图对象,比如刻度、标签
In[12]: ax_children = ax.get_children()
ax_children
Out[12]: [<matplotlib.spines.Spine at 0x11145b358>,
<matplotlib.spines.Spine at 0x11145b0f0>,
<matplotlib.spines.Spine at 0x11145ae80>,
<matplotlib.spines.Spine at 0x11145ac50>,
<matplotlib.axis.XAxis at 0x11145aa90>,
<matplotlib.axis.YAxis at 0x110fa8d30>,
...]
# 通过spines属性直接访问spines
>>> spines = ax.spines
>>> spines
OrderedDict([('left', <matplotlib.spines.Spine at 0x11279e320>),
('right', <matplotlib.spines.Spine at 0x11279e0b8>),
('bottom', <matplotlib.spines.Spine at 0x11279e048>),
('top', <matplotlib.spines.Spine at 0x1127eb5c0>)])
# 选中左边,改变它的位置和宽度,使底边不可见
In[13]: spine_left = spines['left']
spine_left.set_position(('outward', -100))
spine_left.set_linewidth(5)
spine_bottom = spines['bottom']
spine_bottom.set_visible(False)
fig
Out[13]:
# 通过属性xaxis和yaxis可以修改属性,有些属性也可以通过Axes对象直接修改
In[14]: ax.xaxis.grid(True, which='major', linewidth=2, color='black', linestyle='--')
ax.xaxis.set_ticks([.2, .4, .55, .93])
ax.xaxis.set_label_text('X Axis', family='Verdana', fontsize=15)
ax.set_ylabel('Y Axis', family='Calibri', fontsize=20)
ax.set_yticks([.1, .9])
ax.set_yticklabels(['point 1', 'point 9'], rotation=45)
fig
Out[14]:
原理
# plt.subplots函数返回的是一个元组
In[22]: plot_objects = plt.subplots()
In[23]: type(plot_objects)
Out[23]: tuple
In[24]: fig = plot_objects[0]
ax = plot_objects[1]
# 如果创建了多个轴,则元组的第二个元素是一个包含所有轴的NumPy数组
In[25]: plot_objects = plt.subplots(2, 4, figsize=(14, 4))
In[26]: plot_objects[1]
Out[26]: array([[<matplotlib.axes._subplots.AxesSubplot object at 0x113eefa20>,
<matplotlib.axes._subplots.AxesSubplot object at 0x113f7ccc0>,
<matplotlib.axes._subplots.AxesSubplot object at 0x11413ed68>,
<matplotlib.axes._subplots.AxesSubplot object at 0x114213e48>],
[<matplotlib.axes._subplots.AxesSubplot object at 0x11424ce80>,
<matplotlib.axes._subplots.AxesSubplot object at 0x1142807b8>,
<matplotlib.axes._subplots.AxesSubplot object at 0x1142b8898>,
<matplotlib.axes._subplots.AxesSubplot object at 0x1142f2898>]], dtype=object)
# 一些属性和与其等价的get方法
In[27]: fig.get_axes() == fig.axes
Out[27]: True
In[29]: fig.axes == fig.get_axes()
Out[29]: True
In[30]: ax.xaxis == ax.get_xaxis()
Out[30]: True
In[31]: ax.yaxis == ax.get_yaxis()
Out[31]: True
更多
# 查询xaxis的所有属性
In[15]: ax.xaxis.properties()
Out[15]:
{'agg_filter': None,
'alpha': None,
'animated': False,
'children': [Text(0.5,22.2,'X Axis'),
Text(1,23.2,''),
<matplotlib.axis.XTick at 0x113371fd0>,
<matplotlib.axis.XTick at 0x113514240>,
<matplotlib.axis.XTick at 0x1136387b8>,
<matplotlib.axis.XTick at 0x113638f60>],
'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.],
[ 0., 1., 0.],
[ 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.],
[ 0., 72., 0.],
[ 0., 0., 1.]])))))))),
'clip_on': True,
'clip_path': None,
'contains': None,
'data_interval': array([ inf, -inf]),
'figure': <matplotlib.figure.Figure at 0x11332abe0>,
'gid': None,
'gridlines': <a list of 4 Line2D gridline objects>,
'label': Text(0.5,22.2,'X Axis'),
'label_position': 'bottom',
'label_text': 'X Axis',
'major_formatter': <matplotlib.ticker.ScalarFormatter at 0x113543780>,
'major_locator': <matplotlib.ticker.FixedLocator at 0x113648ba8>,
'major_ticks': [<matplotlib.axis.XTick at 0x113371fd0>,
<matplotlib.axis.XTick at 0x113514240>,
<matplotlib.axis.XTick at 0x1136387b8>,
<matplotlib.axis.XTick at 0x113638f60>],
'majorticklabels': <a list of 4 Text major ticklabel objects>,
'majorticklines': <a list of 8 Line2D ticklines objects>,
'majorticklocs': array([ 0.2 , 0.4 , 0.55, 0.93]),
'minor_formatter': <matplotlib.ticker.NullFormatter at 0x11341a518>,
'minor_locator': <matplotlib.ticker.NullLocator at 0x113624198>,
'minor_ticks': [],
'minorticklabels': <a list of 0 Text minor ticklabel objects>,
'minorticklines': <a list of 0 Line2D ticklines objects>,
'minorticklocs': [],
'minpos': inf,
'offset_text': Text(1,23.2,''),
'path_effects': [],
'picker': None,
'pickradius': 15,
'rasterized': None,
'scale': 'linear',
'sketch_params': None,
'smart_bounds': False,
'snap': None,
'tick_padding': 3.5,
'tick_space': 26,
'ticklabels': <a list of 4 Text major ticklabel objects>,
'ticklines': <a list of 8 Line2D ticklines objects>,
'ticklocs': array([ 0.2 , 0.4 , 0.55, 0.93]),
'ticks_direction': array(['out', 'out', 'out', 'out'],
dtype='<U3'),
'ticks_position': 'bottom',
'transform': IdentityTransform(),
'transformed_clip_path_and_affine': (None, None),
'units': None,
'url': None,
'view_interval': array([ 0., 1.]),
'visible': True,
'zorder': 1.5}