使用 Python 创建 Matplotlib 徽标

Beginner

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

简介

在本实验中,你将学习如何使用 Python 创建 Matplotlib 徽标。Matplotlib 库是 Python 中流行的数据可视化工具,广泛应用于科学计算。

虚拟机使用提示

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

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

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

导入所需库

在这一步中,我们将导入必要的库,包括 Matplotlib 和 NumPy。

import matplotlib.pyplot as plt
import numpy as np

定义常量

在这一步中,我们将定义一些常量,包括徽标的颜色和字体。

MPL_BLUE = '#11557c'

def get_font_properties():
    ## 原始字体是 Calibri,如果未安装该字体,我们将回退到 Carlito,它在度量上是等效的。
    if 'Calibri' in matplotlib.font_manager.findfont('Calibri:bold'):
        return matplotlib.font_manager.FontProperties(family='Calibri',
                                                      weight='bold')
    if 'Carlito' in matplotlib.font_manager.findfont('Carlito:bold'):
        print('未找到原始字体。回退到 Carlito。徽标文本的字体将不正确。')
        return matplotlib.font_manager.FontProperties(family='Carlito',
                                                      weight='bold')
    print('未找到原始字体。徽标文本的字体将不正确。')
    return None

创建图标轴

在这一步中,我们将创建一个包含 Matplotlib 雷达图的极坐标轴。

def create_icon_axes(fig, ax_position, lw_bars, lw_grid, lw_border, rgrid):
    """
    创建一个包含 matplotlib 雷达图的极坐标轴。

    参数
    ----------
    fig : matplotlib.figure.Figure
        要绘制到其中的图形。
    ax_position : (float, float, float, float)
        创建的 Axes 在图形坐标中的位置,格式为 (x, y, width, height)。
    lw_bars : float
        条形图的线宽。
    lw_grid : float
        网格的线宽。
    lw_border : float
        Axes 边框的线宽。
    rgrid : 类似数组
        径向网格的位置。

    返回
    -------
    ax : matplotlib.axes.Axes
        创建的 Axes。
    """
    with plt.rc_context({'axes.edgecolor': MPL_BLUE,
                         'axes.linewidth': lw_border}):
        ax = fig.add_axes(ax_position, projection='polar')
        ax.set_axisbelow(True)

        N = 7
        arc = 2. * np.pi
        theta = np.arange(0.0, arc, arc / N)
        radii = np.array([2, 6, 8, 7, 4, 5, 8])
        width = np.pi / 4 * np.array([0.4, 0.4, 0.6, 0.8, 0.2, 0.5, 0.3])
        bars = ax.bar(theta, radii, width=width, bottom=0.0, align='edge',
                      edgecolor='0.3', lw=lw_bars)
        for r, bar in zip(radii, bars):
            color = *cm.jet(r / 10.)[:3], 0.6  ## 来自 jet 颜色映射且透明度为 0.6 的颜色
            bar.set_facecolor(color)

        ax.tick_params(labelbottom=False, labeltop=False,
                       labelleft=False, labelright=False)

        ax.grid(lw=lw_grid, color='0.9')
        ax.set_rmax(9)
        ax.set_yticks(rgrid)

        ## 实际可见的背景 - 延伸到轴外一点
        ax.add_patch(Rectangle((0, 0), arc, 9.58,
                               facecolor='white', zorder=0,
                               clip_on=False, in_layout=False))
        return ax

创建文本轴

在这一步中,我们将在 fig 中创建一个轴,其中包含文本“matplotlib”。

def create_text_axes(fig, height_px):
    """在 *fig* 中创建一个包含文本“matplotlib”的轴。"""
    ax = fig.add_axes((0, 0, 1, 1))
    ax.set_aspect("equal")
    ax.set_axis_off()

    path = TextPath((0, 0), "matplotlib", size=height_px * 0.8,
                    prop=get_font_properties())

    angle = 4.25  ## 度
    trans = mtrans.Affine2D().skew_deg(angle, 0)

    patch = PathPatch(path, transform=trans + ax.transData, color=MPL_BLUE,
                      lw=0)
    ax.add_patch(patch)
    ax.autoscale()

创建徽标

在这一步中,我们将创建带有 Matplotlib 徽标的完整图形。

def make_logo(height_px, lw_bars, lw_grid, lw_border, rgrid, with_text=False):
    """
    创建带有 Matplotlib 徽标的完整图形。

    参数
    ----------
    height_px : int
        图形的高度(以像素为单位)。
    lw_bars : float
        条形图边框的线宽。
    lw_grid : float
        网格的线宽。
    lw_border : float
        图标边框的线宽。
    rgrid : 浮点数序列
        径向网格位置。
    with_text : bool
        是否只绘制图标,还是包含文本“matplotlib”。
    """
    dpi = 100
    height = height_px / dpi
    figsize = (5 * height, height) if with_text else (height, height)
    fig = plt.figure(figsize=figsize, dpi=dpi)
    fig.patch.set_alpha(0)

    if with_text:
        create_text_axes(fig, height_px)
    ax_pos = (0.535, 0.12,.17, 0.75) if with_text else (0.03, 0.03,.94,.94)
    ax = create_icon_axes(fig, ax_pos, lw_bars, lw_grid, lw_border, rgrid)

    return fig, ax

显示徽标

在这一步中,我们将显示不同大小的 Matplotlib 徽标。

## 一个大徽标:
make_logo(height_px=110, lw_bars=0.7, lw_grid=0.5, lw_border=1,
          rgrid=[1, 3, 5, 7])

## 一个 32 像素的小徽标:
make_logo(height_px=32, lw_bars=0.3, lw_grid=0.3, lw_border=0.3, rgrid=[5])

## 一个包含文本的大徽标,如 Matplotlib 网站上使用的那样。
make_logo(height_px=110, lw_bars=0.7, lw_grid=0.5, lw_border=1,
          rgrid=[1, 3, 5, 7], with_text=True)
plt.show()

总结

在这个实验中,你学习了如何使用 Python 创建 Matplotlib 徽标。通过遵循上述步骤,你可以根据自己的需求和偏好自定义徽标。