Matplotlib

Chapter 9: Plotting and Visualization

颜⾊、标记和线型

matplotlib的plot函数接受⼀组X和Y坐标,还可以接受⼀个表示颜 ⾊和线型的字符串缩写。例如,要根据x和y绘制绿⾊虚线,你可 以执⾏如下代码:

ax.plot(x, y, 'g--')

这种在⼀个字符串中指定颜⾊和线型的⽅式⾮常⽅便。在实际 中,如果你是⽤代码绘图,你可能不想通过处理字符串来获得想 要的格式。通过下⾯这种更为明确的⽅式也能得到同样的效果:

ax.plot(x, y, linestyle='--', color='g') 

常⽤的颜⾊可以使⽤颜⾊缩写,你也可以指定颜⾊码(例 如,'#CECECE')。你可以通过查看plot的⽂档字符串查看所有 线型的合集(在IPython和Jupyter中使⽤plot?)。
线图可以使⽤标记强调数据点。因为matplotlib可以创建连续线 图,在点之间进⾏插值,因此有时可能不太容易看出真实数据点 的位置。标记也可以放到格式字符串中,但标记类型和线型必须 放在颜⾊后⾯(⻅图9-6):

In [30]: from numpy.random import randn 
In  [31]: plt.plot(randn(30).cumsum(), 'ko--')
Figure_1.png

还能写成更明确的形式:

plot(randn(30).cumsum(), color = 'k', linestype = 'dashed', marker = 'o')

在线型图中,⾮实际数据点默认是按线性⽅式插值的。可以通过 drawstyle选项修改(⻅图9-7):

In [33]: data = np.random.randn(30).cumsum()
In [34]: plt.plot(data, 'k--', label='Default') 
Out[34]: [<matplotlib.lines.Line2D at 0x7fb624d86160>]
In [35]: plt.plot(data, 'k-', drawstyle='steps-post', label='steps-post') 
Out[35]: [<matplotlib.lines.Line2D at 0x7fb624d869e8>]
In [36]: plt.legend(loc='best')
Figure9-7.png

你可能注意到运⾏上⾯代码时有输出<matplotlib.lines.Line2D at ...>。matplotlib会返回引⽤了新添加的⼦组件的对象。⼤多数时 候,你可以放⼼地忽略这些输出。这⾥,因为我们传递了label参 数到plot,我们可以创建⼀个plot图例,指明每条使⽤plt.legend
347的线。

笔记:你必须调⽤plt.legend(或使⽤ax.legend,如果引⽤了 轴的话)来创建图例,⽆论你绘图时是否传递label标签选 项。

刻度、标签和图例

对于⼤多数的图表装饰项,其主要实现⽅式有⼆:使⽤过程型的 pyplot接⼝(例如,matplotlib.pyplot)以及更为⾯向对象的原⽣ matplotlib API。
pyplot接⼝的设计⽬的就是交互式使⽤,含有诸如xlim、xticks和 xticklabels之类的⽅法。它们分别控制图表的范围、刻度位置、 刻度标签等。其使⽤⽅式有以下两种:

  • 调⽤时不带参数,则返回当前的参数值(例如,plt.xlim()返回 当前的X轴绘图范围)。
  • 调⽤时带参数,则设置参数值(例如,plt.xlim([0,10])会将X轴 的范围设置为0到10)。

所有这些⽅法都是对当前或最近创建的AxesSubplot起作⽤的。 它们各⾃对应subplot对象上的两个⽅法,以xlim为例,就是 ax.get_xlim和ax.set_xlim。我更喜欢使⽤subplot的实例⽅法 (因为我喜欢明确的事情,⽽且在处理多个subplot时这样也更清 楚⼀些)。当然你完全可以选择⾃⼰觉得⽅便的那个。

设置标题、轴标签、刻度以及刻度标签

为了说明⾃定义轴,我将创建⼀个简单的图像并绘制⼀段随机漫 步(如图9-8所示):

In [37]: fig = plt.figure() 
In [38]: ax = fig.add_subplot(1, 1, 1) 
In [39]: ax.plot(np.random.randn(1000).cumsum())
Figure 9-8.png

要改变x轴刻度,最简单的办法是使⽤set_xticks和 set_xticklabels。前者告诉matplotlib要将刻度放在数据范围中的 哪些位置,默认情况下,这些位置也就是刻度标签。但我们可以 通过set_xticklabels将任何其他的值⽤作标签:

In [40]: ticks = ax.set_xticks([0, 250, 500, 750, 1000])
In [41]: labels = ax.set_xticklabels(['one', 'two', 'three', 'four', 'five'], 
   ....:                                  rotation=30, fontsize='small')

The rotation option sets the x tick labels at a 30-degree rotation. Lastly, set_xlabel gives a name to the x-axis and set_title the subplot title (see Figure 9-9 for the resulting figure):

In [42]: ax.set_title('My first matplotlib plot') 
Out[42]: <matplotlib.text.Text at 0x7fb624d055f8> 
In [43]: ax.set_xlabel('Stages')
Figure 9-9.png

Modifying the y-axis consists of the same process, substituting y for x in the above. The axes class has a set method that allows batch setting of plot properties. From the prior example, we could also have written:

props = {
 'title': 'My first matplotlib plot',
 'xlabel': 'Stages'
} 
ax.set(**props)

Adding legends

Legends are another critical element for identifying plot elements. There are a couple of ways to add one. The easiest is to pass the label argument when adding each piece of the plot: In [44]: from numpy.random import randn

In [45]: fig = plt.figure(); ax = fig.add_subplot(1, 1, 1)

In [46]: ax.plot(randn(1000).cumsum(), 'k', label='one') 
Out[46]: [<matplotlib.lines.Line2D at 0x7fb624bdf860>]

In [47]: ax.plot(randn(1000).cumsum(), 'k--', label='two') 
Out[47]: [<matplotlib.lines.Line2D at 0x7fb624be90f0>]

In [48]: ax.plot(randn(1000).cumsum(), 'k.', label='three') 
Out[48]: [<matplotlib.lines.Line2D at 0x7fb624be9160>]

Once you’ve done this, you can either call ax.legend() or plt.legend() to automatically create a legend. The resulting plot is in Figure 9-10:

 In [49]: ax.legend(loc='best') 
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容