Matplotlib-bar-plot

提供:Dev Guides
移動先:案内検索

Matplotlib-バープロット

棒グラフまたは棒グラフは、カテゴリデータを、それらが表す値に比例した高さまたは長さの長方形の棒で表すデータです。 バーは垂直または水平にプロットできます。

棒グラフは、個別のカテゴリ間の比較を示します。 チャートの1つの軸は比較される特定のカテゴリを示し、もう1つの軸は測定値を表します。

Matplotlib APIは、オブジェクト指向APIと同様に、MATLABスタイルで使用できる* bar()*関数を提供します。 Axesオブジェクトで使用されるbar()関数のシグネチャは次のとおりです-

ax.bar(x, height, width, bottom, align)

この関数は、サイズ(x -width = 2; x + width = 2; bottom; bottom + height)のバインドされた長方形で棒グラフを作成します。

関数へのパラメータは-

x sequence of scalars representing the x coordinates of the bars. align controls if x is the bar center (default) or left edge.
height scalar or sequence of scalars representing the height(s) of the bars.
width scalar or array-like, optional. the width(s) of the bars default 0.8
bottom scalar or array-like, optional. the y coordinate(s) of the bars default None.
align \{‘center’, ‘edge’}, optional, default ‘center’

この関数は、すべてのバーを含むMatplotlibコンテナオブジェクトを返します。

以下は、Matplotlib棒グラフの簡単な例です。 研究所で提供されるさまざまなコースに登録している学生の数を示しています。

import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
langs = ['C', 'C++', 'Java', 'Python', 'PHP']
students = [23,17,35,29,12]
ax.bar(langs,students)
plt.show()

Matplotlibバープロット

複数の数量を比較し、1つの変数を変更する場合、1つの数量値に対して1つの色の棒がある棒グラフが必要になる場合があります。

棒の太さと位置で遊んで、複数の棒グラフをプロットできます。 データ変数には、4つの値の3つのシリーズが含まれます。 次のスクリプトは、4つの棒の3つの棒グラフを表示します。 バーの厚さは0.25単位になります。 各棒グラフは、前の棒グラフから0.25単位シフトします。 データオブジェクトは、過去4年間にエンジニアリングカレッジの3つのブランチに合格した学生の数を含むマルチディクトです。

import numpy as np
import matplotlib.pyplot as plt
data = [[X = np.arange(4)
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.bar(X + 0.00, data[0], color = 'b', width = 0.25)
ax.bar(X + 0.25, data[1], color = 'g', width = 0.25)
ax.bar(X + 0.50, data[2], color = 'r', width = 0.25)

複数の棒グラフ

積み上げ棒グラフは、異なるグループを表す棒を積み上げます。 結果のバーの高さは、グループの結合結果を示します。

  • pyplot.bar()*関数のオプションのbottomパラメーターを使用すると、バーの開始値を指定できます。 ゼロから値に実行する代わりに、下から値に移動します。 pyplot.bar()の最初の呼び出しは、青いバーをプロットします。 pyplot.bar()の2回目の呼び出しは、赤いバーをプロットします。青いバーの下部が赤いバーの上部にあります。
import numpy as np
import matplotlib.pyplot as plt
N = 5
menMeans = (20, 35, 30, 35, 27)
womenMeans = (25, 32, 34, 20, 25)
ind = np.arange(N) # the x locations for the groups
width = 0.35
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.bar(ind, menMeans, width, color='r')
ax.bar(ind, womenMeans, width,bottom=menMeans, color='b')
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(ind, ('G1', 'G2', 'G3', 'G4', 'G5'))
ax.set_yticks(np.arange(0, 81, 10))
ax.legend(labels=['Men', 'Women'])
plt.show()

スコア