Matplotlib を使ったラベル付き棒グラフ

PythonPythonBeginner
今すぐ練習

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

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

はじめに

このチュートリアルでは、Matplotlibのbar_labelヘルパー関数を使ってラベル付きの棒グラフを作成する方法を学びます。水平および垂直の棒グラフにラベルを付ける、異なるラベル形式を使う、およびラベルの外観をカスタマイズするなど、様々なシナリオに対応します。

VMのヒント

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

時々、Jupyter Notebookが読み込み終了するまで数秒待つ必要があります。Jupyter Notebookの制限により、操作の検証を自動化することはできません。

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

ライブラリのインポート

まず、必要なライブラリをインポートする必要があります。それには、numpymatplotlib が含まれます。また、numpyrandom モジュールを使って、いくつかのランダムなデータを生成します。

import matplotlib.pyplot as plt
import numpy as np

## Fixing random state for reproducibility
np.random.seed(19680801)

垂直棒グラフのラベリング

まず、垂直棒グラフを作成して、bar_label関数を使ってそれにラベルを付けます。使用するデータは、性別別のペンギンの数で、https://allisonhorst.github.io/palmerpenguins/ から取得しました。

species = ('Adelie', 'Chinstrap', 'Gentoo')
sex_counts = {
    'Male': np.array([73, 34, 61]),
    'Female': np.array([73, 34, 58]),
}
width = 0.6  ## the width of the bars: can also be len(x) sequence

fig, ax = plt.subplots()
bottom = np.zeros(3)

for sex, sex_count in sex_counts.items():
    p = ax.bar(species, sex_count, width, label=sex, bottom=bottom)
    bottom += sex_count

    ax.bar_label(p, label_type='center')

ax.set_title('Number of penguins by sex')
ax.legend()

plt.show()

水平棒グラフのラベリング

次に、水平棒グラフを作成して、bar_label関数を使ってそれにラベルを付けます。前のステップのデータを使いますが、今回はそれぞれの人に対していくつかのランダムなパフォーマンスデータを生成します。

people = ('Tom', 'Dick', 'Harry', 'Slim', 'Jim')
y_pos = np.arange(len(people))
performance = 3 + 10 * np.random.rand(len(people))
error = np.random.rand(len(people))

fig, ax = plt.subplots()

hbars = ax.barh(y_pos, performance, xerr=error, align='center')
ax.set_yticks(y_pos, labels=people)
ax.invert_yaxis()  ## labels read top-to-bottom
ax.set_xlabel('Performance')
ax.set_title('How fast do you want to go today?')

## Label with specially formatted floats
ax.bar_label(hbars, fmt='%.2f')
ax.set_xlim(right=15)  ## adjust xlim to fit labels

plt.show()

高度な棒グラフのラベリング

このステップでは、棒グラフのラベルに関して行えるさらに高度なことをいくつか示します。前のステップと同じ水平棒グラフを使用します。

fig, ax = plt.subplots()

hbars = ax.barh(y_pos, performance, xerr=error, align='center')
ax.set_yticks(y_pos, labels=people)
ax.invert_yaxis()  ## labels read top-to-bottom
ax.set_xlabel('Performance')
ax.set_title('How fast do you want to go today?')

## Label with given captions, custom padding and annotate options
ax.bar_label(hbars, labels=[f'±{e:.2f}' for e in error],
             padding=8, color='b', fontsize=14)
ax.set_xlim(right=16)

plt.show()

{} スタイルの書式指定文字列を使用した棒グラフのラベリング

このステップでは、棒グラフのラベルを書式設定するために {} スタイルの書式指定文字列をどのように使用するかを示します。アイスクリームの味別売上データをいくつか使います。

fruit_names = ['Coffee', 'Salted Caramel', 'Pistachio']
fruit_counts = [4000, 2000, 7000]

fig, ax = plt.subplots()
bar_container = ax.bar(fruit_names, fruit_counts)
ax.set(ylabel='pints sold', title='Gelato sales by flavor', ylim=(0, 8000))
ax.bar_label(bar_container, fmt='{:,.0f}')

コール可能オブジェクトを使用した棒グラフのラベリング

最後に、コール可能オブジェクトを使用して棒グラフのラベルを書式設定する方法を示します。異なる動物の走行速度に関するいくつかのデータを使用します。

animal_names = ['Lion', 'Gazelle', 'Cheetah']
mph_speed = [50, 60, 75]

fig, ax = plt.subplots()
bar_container = ax.bar(animal_names, mph_speed)
ax.set(ylabel='speed in MPH', title='Running speeds', ylim=(0, 80))
ax.bar_label(bar_container, fmt=lambda x: f'{x * 1.61:.1f} km/h')

まとめ

このチュートリアルでは、Matplotlibのbar_labelヘルパー関数を使ってラベル付きの棒グラフを作成する方法を学びました。水平および垂直の棒グラフにラベルを付ける、異なるラベル形式を使用する、およびラベルの外観をカスタマイズするなど、さまざまなシナリオについて説明しました。