Python を使って Matplotlib のロゴを作成する

PythonPythonBeginner
今すぐ練習

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

💡 このチュートリアルは英語版からAIによって翻訳されています。原文を確認するには、 ここをクリックしてください

はじめに

この実験では、Python を使って Matplotlib のロゴを作成する方法を学びます。Matplotlib ライブラリは、Python 用の人気のあるデータ可視化ツールであり、科学計算で広く使用されています。

VM のヒント

VM の起動が完了したら、左上隅をクリックして ノートブック タブに切り替え、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' をテキストとして含む Axes を作成します。"""
    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])

## 小さな 32px のロゴ:
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 のロゴを作成する方法を学びました。上記の手順に従えば、必要や好みに合わせてロゴをカスタマイズすることができます。