Matplotlibによるグラフ作成 第2回
PythonのMatplotlibを使用した基本的なグラフ作成方法を紹介する
今回は、頻度
を比較するヒストグラム
の作成方法を紹介する
サンプルデータ生成
2種類の正規分布を用意する
import matplotlib.pyplot as plt import numpy as np mean1 = 10 sigma1 = 5 N1 = 1000 data1 = np.random.normal(mean1, sigma1, N1) mean2 = 40 sigma2 = 10 N2 = 1000 data2 = np.random.normal(mean2, sigma2, N2)
隣り合わせのヒストグラム
fig = plt.figure(figsize=(6, 5)) ax = fig.add_subplot(111) ax.hist([data1, data2], label=['DATA1', 'DATA2']) ax.legend() ax.grid() ax.set_ylabel('count') fig.tight_layout()
積み上げヒストグラム
fig = plt.figure(figsize=(6, 5)) ax = fig.add_subplot(111) ax.hist([data1, data2], histtype='barstacked', label=['DATA1', 'DATA2']) ax.legend() ax.grid() ax.set_ylabel('count') fig.tight_layout()
重ね書きヒストグラム
fig = plt.figure(figsize=(6, 5)) ax = fig.add_subplot(111) ax.hist(data1, label='DATA1', alpha=1.0) ax.hist(data2, label='DATA2', alpha=0.6) ax.legend() ax.grid() ax.set_ylabel('count') fig.tight_layout()
積み上げヒストグラムの微調整
fig = plt.figure(figsize=(6, 5)) ax = fig.add_subplot(111) ax.hist( [data1, data2], bins=25, range=[-15, 75], histtype='barstacked', label=['DATA1', 'DATA2'] ) ax.legend() ax.grid() ax.set_ylabel('count') fig.tight_layout()