Matplotlib のスパイン配置

PythonPythonBeginner
今すぐ練習

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

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

はじめに

Matplotlib では、軸のスパインの位置を調整することでグラフの外観をカスタマイズできます。この実験では、Matplotlib でスパインの位置を調整する手順を案内します。

VM のヒント

VM の起動が完了したら、左上隅をクリックして ノートブック タブに切り替え、Jupyter Notebook を使って練習しましょう。

Jupyter Notebook の読み込みには数秒かかる場合があります。Jupyter Notebook の制限により、操作の検証は自動化できません。

学習中に問題がある場合は、Labby にお問い合わせください。セッション終了後にフィードバックを提供してください。すぐに問題を解決いたします。

必要なライブラリをインポートする

このステップでは、グラフを作成するために必要なライブラリをインポートします。

import matplotlib.pyplot as plt
import numpy as np

基本的なグラフを作成する

このステップでは、Matplotlib のさまざまなスパイン配置オプションを示すために、基本的なグラフを作成します。

x = np.linspace(0, 2*np.pi, 100)
y = 2 * np.sin(x)

fig, ax_dict = plt.subplot_mosaic(
    [['center', 'zero'],
     ['axes', 'data']]
)
fig.suptitle('Spine positions')

ax = ax_dict['center']
ax.set_title("'center'")
ax.plot(x, y)
ax.spines[['left', 'bottom']].set_position('center')
ax.spines[['top', 'right']].set_visible(False)

ax = ax_dict['zero']
ax.set_title("'zero'")
ax.plot(x, y)
ax.spines[['left', 'bottom']].set_position('zero')
ax.spines[['top', 'right']].set_visible(False)

ax = ax_dict['axes']
ax.set_title("'axes' (0.2, 0.2)")
ax.plot(x, y)
ax.spines.left.set_position(('axes', 0.2))
ax.spines.bottom.set_position(('axes', 0.2))
ax.spines[['top', 'right']].set_visible(False)

ax = ax_dict['data']
ax.set_title("'data' (1, 2)")
ax.plot(x, y)
ax.spines.left.set_position(('data', 1))
ax.spines.bottom.set_position(('data', 2))
ax.spines[['top', 'right']].set_visible(False)

スパインの位置を調整するメソッドを定義する

このステップでは、指定されたスパインの位置に基づいて軸のスパインの位置を調整するメソッドを定義します。

def adjust_spines(ax, spines):
    """
    Adjusts the location of the axis spines based on the specified spine locations.

    Parameters:
        ax (Axes): The Matplotlib Axes object to adjust the spines for.
        spines (list of str): The desired spine locations. Valid options are 'left', 'right', 'top', 'bottom'.

    Returns:
        None
    """
    for loc, spine in ax.spines.items():
        if loc in spines:
            spine.set_position(('outward', 10))  ## move the spine outward by 10 points
        else:
            spine.set_color('none')  ## don't draw the spine

    ## turn off ticks where there is no spine
    if 'left' in spines:
        ax.yaxis.set_ticks_position('left')
    else:
        ax.yaxis.set_ticks([])

    if 'bottom' in spines:
        ax.xaxis.set_ticks_position('bottom')
    else:
        ax.xaxis.set_ticks([])

adjust_spines メソッドを使ってグラフを作成する

このステップでは、スパインの位置を調整する方法を示すために、adjust_spines メソッドを使ってグラフを作成します。

fig = plt.figure()

x = np.linspace(0, 2 * np.pi, 100)
y = 2 * np.sin(x)

ax = fig.add_subplot(2, 2, 1)
ax.plot(x, y, clip_on=False)
adjust_spines(ax, ['left'])

ax = fig.add_subplot(2, 2, 2)
ax.plot(x, y, clip_on=False)
adjust_spines(ax, [])

ax = fig.add_subplot(2, 2, 3)
ax.plot(x, y, clip_on=False)
adjust_spines(ax, ['left', 'bottom'])

ax = fig.add_subplot(2, 2, 4)
ax.plot(x, y, clip_on=False)
adjust_spines(ax, ['bottom'])

plt.show()

まとめ

この実験では、Matplotlib で軸のスパインの位置を set_position メソッドを使って設定することでスパインの位置を調整する方法と、望ましいスパインの位置に基づいてスパインの位置を調整するメソッドを定義する方法を学びました。これは、グラフの外観をカスタマイズし、特定の機能を強調する際に役立ちます。