关于机器学习:Matplotlib进行数据可视化的快速上手指南

2次阅读

共计 3966 个字符,预计需要花费 10 分钟才能阅读完成。

图表是数据摸索过程的根底,它们让咱们更好地了解咱们的数据——例如,帮忙辨认异样值或所须要做的数据处理或者作为建设机器学习模型提供新的想法和形式。绘制图表是任何数据迷信报告的重要组成部分。

Python 有许多可视化库用于制作动态或动态图。在本教程中,我将尽力帮忙你了解 matplotlib 逻辑。

Matplotlib 是 Python 绘图库的重要组成部分,创立它是为了在 Python 中启用相似 MATLAB 的绘图界面。如果没有 MATLAB 背景,可能很难了解所有 matplotlib 局部如何协同工作以创立想要的图形。不过别放心,本教程将把它分解成逻辑组件以疾速上手。

图形对象

Matplotlib 是分层的。Figure 对象由轴(或子图)组成;每个轴都定义了一个具备不同图对象(题目、图例、刻度、轴)。下图阐明了 matplotlib 图的各种组件。

要创立图形,能够应用“pyplot.figure”函数,或应用“pyplot.add_subplot”函数向图中增加轴。

# import matplotlib and Numpy
import matplotlib.pyplot as plt
import numpy as np
# magic command to show figures in jupyter notebook
%matplotlib inline

# create a figure
fig = plt.figure()
# add axes
ax1 = fig.add_subplot(2, 2, 1)
ax2 = fig.add_subplot(2, 2, 2)
ax3 = fig.add_subplot(2, 2, 3)

在下面的代码片段中,咱们定义了一个图形,总共最多蕴含 4 个图。咱们正在抉择四个子图中的三个。

一个简略的办法是应用“plt.subplots”函数创立一个带轴的图形。

fig, axes = plt.subplots(2, 2)
# first subplot
axes[0, 0].scatter(np.arange(40), np.arange(40) + 4 * np.random.randn(40))
# second subplot
axes[0, 1].plot(np.random.randn(40).cumsum())
# third subplot
_ = axes[1, 0].hist(np.random.randn(100), bins=20)
# fourth subplot
axes[1, 1].bar(np.arange(40), np.arange(40) + 4 * np.random.randn(40))
plt.tight_layout()

上图蕴含不同子图类型。能够在 matplotlib 文档中找到残缺的绘图类型目录。

‘Plt.tight_layout()’函数用于很好地主动距离子图并防止拥挤。此外,还能够应用‘plt.subplots_adjust (left = None, bottom = None, top = None, wspace = None, hspace = None)’函数更改图形对象的默认间距。

fig, axes = plt.subplots(2, 2, sharex=True, sharey=True)
for i in range(2):
    for j in range(2):
        axes[i, j].plot(np.random.randn(40).cumsum())
plt.subplots_adjust(wspace=0, hspace=0)

线型、色彩和标记

“plt.plot”函数能够抉择承受一个字符串缩写,示意色彩和线条款式。例如咱们在上面的代码片段中绘制了一条红色虚线。

fig, ax = plt.subplots()
ax.plot(np.random.randn(30), 'r--')

咱们能够通过应用 linestyle 和 color 属性来指定线型和色彩。

fig, ax = plt.subplots(1, 1)
ax.plot(np.random.randn(30), linestyle='--', color='r')

matplotlib 中可用的线型有:

‘-’: 实线款式‘—‘: 虚线款式‘-.’: 点划线款式‘:’: 虚线款式 

除了 matplotlib 提供的色彩缩写之外,咱们还能够通过指定其十六进制代码(例如,‘FFFF’)来应用光谱上的任何色彩。

为了绘制线图,matplotlib 在点之间进行插值。能够应用“marker”属性来突出显示理论数据点,如下图所示。

fig, ax = plt.subplots(1, 1)
ax.plot(np.random.randn(30), linestyle='dashed', color='k', marker='o')

默认插值是线性的;然而能够应用“drawstyle”属性更改它。上面的示例阐明了线性插值和步进后插值。

# data
data = np.random.randn(20).cumsum()
# figure
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 4))
ax1.plot(data, 'k--')
ax2.plot(data, 'b-', drawstyle='steps-post')

刻度和标签

ax 对象(子图对象)有不同的办法来自定义绘图:

  • ‘Set_xticks’和 set_xticklabels’扭转 x 轴刻度;
  • ‘Set_yticks’和 set_yticklabels’扭转 y 轴刻度;
  • Set_title ‘ 为绘图增加题目。
fig, ax = plt.subplots(1, 1)
ax.plot(np.random.randn(1000).cumsum())
ticks = ax.set_xticks([0, 200, 400, 600, 800, 1000])
labels = ax.set_xticklabels(['one', 'two', 'three', 'four', 'five', 'six'],
                           rotation=30, fontsize=12)
ax.set_title('Matplotlib plot')
ax.set_xlabel('Stages', fontsize=12)

另一种设置绘图属性的办法是应用属性字典的“set”办法。

fig, ax = plt.subplots(1, 1)
ax.plot(np.random.randn(1000).cumsum())
props = {
    'title': 'Matplotlib title',
    'xlabel': 'Stages'
}
ax.set(**props)

在同一图中绘制不同数据时,图例对于辨认图元素至关重要。因而,咱们应用标签“label 和 legend”办法来增加图例。

fig, ax = plt.subplots(1, 1)
ax.plot(np.random.randn(500).cumsum(), 'k', label='First plot')
ax.plot(np.random.randn(500).cumsum(), 'k--', label='Second plot')
ax.plot(np.random.randn(500).cumsum(), 'k.', label='Third plot')
ax.legend(loc='best')

正文

要向子图增加正文,咱们能够应用“text”、“arrow”和 annotation 函数。text 会在绘图上的给定坐标 (x, y) 处应用可选的自定义款式绘制文本。

fig, ax = plt.subplots()
ax.plot(np.arange(30), 'k')
ax.text(5, 15, 'Hello world!',
        family='monospace', fontsize=10)

“annotation”办法能够将文字和箭头适当排列。

fig, ax = plt.subplots()
ax.plot(np.linspace(0, 10, 200), np.sin(np.linspace(0, 10, 200)))
ax.annotate('Min', xy=(4.7, -1),
           xytext=(4.5, -0.5),
           arrowprops=dict(facecolor='black', headwidth=6, width=3,
                          headlength=4),
          horizontalalignment='left', verticalalignment='top')
ax.set_title('Annotation example')

Matplotlib 具备代表许多规范形态的对象,称为 patches。像 Rectangle 和 Circle 一样,有些在‘matplotlib.pyplot’中,但整个汇合在‘matplotlib.patches’中。

fig, ax = plt.subplots()

rect = plt.Rectangle((0.2, 0.75), 0.4, 0.15, color='k', alpha=0.3)
circ = plt.Circle((0.7, 0.2), 0.15, color='b', alpha=0.3)
pgon = plt.Polygon([[0.15, 0.15], [0.35, 0.4], [0.2, 0.6]],
                    color='g', alpha=0.5)
ax.add_patch(rect)
ax.add_patch(circ)
ax.add_patch(pgon)

保留图像

能够应用“fig.savefig”将要绘图保留在文件中。Matplotlib 会从文件扩展名推断文件类型。例如咱们应用以下代码来保留图形的 PDF 版本。

fig.savefig(‘figpath.pdf’)

总结

本教程的指标是让你相熟应用 matplotlib 进行数据可视化的基础知识。心愿本篇文章可能对你的工作有所帮忙。

作者:Jaouad Eddadsi

正文完
 0