Matplotlib 样式表

PythonPythonBeginner
立即练习

This tutorial is from open-source community. Access the source code

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

Matplotlib 是 Python 中一个强大的数据可视化库。它允许你创建各种图表,如散点图、直方图、条形图等等。样式表参考脚本在一组通用的示例图表上展示了不同的可用样式表。在本实验中,你将学习如何使用 Matplotlib 样式表来自定义图表的外观。

虚拟机使用提示

虚拟机启动完成后,点击左上角切换到“笔记本”标签页以访问 Jupyter Notebook 进行练习。

有时,你可能需要等待几秒钟让 Jupyter Notebook 完成加载。由于 Jupyter Notebook 的限制,操作验证无法自动化。

如果你在学习过程中遇到问题,随时向 Labby 提问。课程结束后提供反馈,我们会立即为你解决问题。

导入库

在开始之前,你需要导入必要的库。在本实验中,你将使用 Matplotlib 和 NumPy。

import matplotlib.pyplot as plt
import numpy as np

定义绘图函数

接下来,你需要定义用于创建示例图表的绘图函数。在这一步中,你将定义以下绘图函数:

  • plot_scatter():创建散点图
  • plot_colored_lines():按照样式颜色循环绘制带颜色的线条
  • plot_bar_graphs():创建条形图
  • plot_colored_circles():绘制圆形补丁
  • plot_image_and_patch():绘制带有圆形补丁的图像
  • plot_histograms():创建直方图
def plot_scatter(ax, prng, nb_samples=100):
    """散点图。"""
    for mu, sigma, marker in [(-.5, 0.75, 'o'), (0.75, 1.,'s')]:
        x, y = prng.normal(loc=mu, scale=sigma, size=(2, nb_samples))
        ax.plot(x, y, ls='none', marker=marker)
    ax.set_xlabel('X 轴标签')
    ax.set_title('坐标轴标题')
    return ax


def plot_colored_lines(ax):
    """按照样式颜色循环绘制带颜色的线条。"""
    t = np.linspace(-10, 10, 100)

    def sigmoid(t, t0):
        return 1 / (1 + np.exp(-(t - t0)))

    nb_colors = len(plt.rcParams['axes.prop_cycle'])
    shifts = np.linspace(-5, 5, nb_colors)
    amplitudes = np.linspace(1, 1.5, nb_colors)
    for t0, a in zip(shifts, amplitudes):
        ax.plot(t, a * sigmoid(t, t0), '-')
    ax.set_xlim(-10, 10)
    return ax


def plot_bar_graphs(ax, prng, min_value=5, max_value=25, nb_samples=5):
    """并排绘制两个条形图,x 轴刻度标签为字母。"""
    x = np.arange(nb_samples)
    ya, yb = prng.randint(min_value, max_value, size=(2, nb_samples))
    width = 0.25
    ax.bar(x, ya, width)
    ax.bar(x + width, yb, width, color='C2')
    ax.set_xticks(x + width, labels=['a', 'b', 'c', 'd', 'e'])
    return ax


def plot_colored_circles(ax, prng, nb_samples=15):
    """
    绘制圆形补丁。

    注意:绘制固定数量的样本,而不是使用颜色循环的长度,因为不同的样式可能有不同数量的颜色。
    """
    for sty_dict, j in zip(plt.rcParams['axes.prop_cycle'](),
                           range(nb_samples)):
        ax.add_patch(plt.Circle(prng.normal(scale=3, size=2),
                                radius=1.0, color=sty_dict['color']))
    ax.grid(visible=True)

    ## 添加标题以启用网格
    plt.title('ax.grid(True)', family='monospace', fontsize='small')

    ax.set_xlim([-4, 8])
    ax.set_ylim([-5, 6])
    ax.set_aspect('equal', adjustable='box')  ## 将圆形绘制为圆形
    return ax


def plot_image_and_patch(ax, prng, size=(20, 20)):
    """绘制具有随机值的图像并叠加一个圆形补丁。"""
    values = prng.random_sample(size=size)
    ax.imshow(values, interpolation='none')
    c = plt.Circle((5, 5), radius=5, label='patch')
    ax.add_patch(c)
    ## 移除刻度
    ax.set_xticks([])
    ax.set_yticks([])


def plot_histograms(ax, prng, nb_samples=10000):
    """绘制 4 个直方图和一个文本注释。"""
    params = ((10, 10), (4, 12), (50, 12), (6, 55))
    for a, b in params:
        values = prng.beta(a, b, size=nb_samples)
        ax.hist(values, histtype="stepfilled", bins=30,
                alpha=0.8, density=True)

    ## 添加一个小注释。
    ax.annotate('注释', xy=(0.25, 4.25),
                xytext=(0.9, 0.9), textcoords=ax.transAxes,
                va="top", ha="right",
                bbox=dict(boxstyle="round", alpha=0.2),
                arrowprops=dict(
                          arrowstyle="->",
                          connectionstyle="angle,angleA=-95,angleB=35,rad=10"),
                )
    return ax

定义绘图函数

现在,你需要定义 plot_figure() 函数,该函数将使用给定的样式设置并绘制演示图形。此函数将调用步骤 2 中定义的每个绘图函数。

def plot_figure(style_label=""):
    """使用给定的样式设置并绘制演示图形。"""
    ## 使用专用的 RandomState 实例来绘制不同图形上相同的“随机”值
    prng = np.random.RandomState(96917002)

    fig, axs = plt.subplots(ncols=6, nrows=1, num=style_label,
                            figsize=(14.8, 2.8), layout='constrained')

    ## 制作一个总标题,所有子图使用相同的样式,
    ## 除了那些背景较暗的子图,它们使用较浅的颜色:
    background_color = mcolors.rgb_to_hsv(
        mcolors.to_rgb(plt.rcParams['figure.facecolor']))[2]
    if background_color < 0.5:
        title_color = [0.8, 0.8, 1]
    else:
        title_color = np.array([19, 6, 84]) / 256
    fig.suptitle(style_label, x=0.01, ha='left', color=title_color,
                 fontsize=14, fontfamily='DejaVu Sans', fontweight='normal')

    plot_scatter(axs[0], prng)
    plot_image_and_patch(axs[1], prng)
    plot_bar_graphs(axs[2], prng)
    plot_colored_lines(axs[3])
    plot_histograms(axs[4], prng)
    plot_colored_circles(axs[5], prng)

    ## 添加分隔线
    rec = Rectangle((1 + 0.025, -2), 0.05, 16,
                    clip_on=False, color='gray')

    axs[4].add_artist(rec)

为每个样式表绘制演示图形

最后,你需要为每个可用的样式表绘制演示图形。你可以通过遍历 style_list 并为每个样式表调用 plot_figure() 函数来实现这一点。

if __name__ == "__main__":

    ## 设置一个按字母顺序排列的所有可用样式的列表,但
    ## `default` 和 `classic` 样式将分别强制排在第一和第二位。
    ## 带有前导下划线的样式用于内部使用,例如测试
    ## 和绘图类型图库。这里将它们排除在外。
    style_list = ['default', 'classic'] + sorted(
        style for style in plt.style.available
        if style!= 'classic' and not style.startswith('_'))

    ## 为每个可用的样式表绘制一个演示图形。
    for style_label in style_list:
        with plt.rc_context({"figure.max_open_warning": len(style_list)}):
            with plt.style.context(style_label):
                plot_figure(style_label=style_label)

    plt.show()

总结

在本实验中,你学习了如何使用 Matplotlib 样式表来定制图表的外观。你学习了如何定义绘图函数,并使用它们来创建具有给定样式表的演示图形。通过遵循本实验中概述的步骤,你可以将 Matplotlib 样式表应用于自己的图表,以创建看起来专业的数据可视化效果。