hist【ヒストグラム】

メモ ( 基本 積み上げ 累積 データの指定方法 関連設定 ) 構文 設定・グラフパーツ

メモ

histのサンプル

基本

積み上げ

累積

データの指定方法

関連設定


構文

pyplot.hist(
    x (データ)※data,
    bins (ビン指定)=None,
    range (ビンの範囲)=None,
    density (正規化の有無)=False,
    weights (データの重み)※data =None,
    cumulative (累積の有無)=False,
    bottom (下部位置)=None,
    histtype (スタイル)='bar',
    align (寄せ)='mid',
    orientation (バーの向き)='vertical',
    rwidth (バーの相対幅)=None,
    log (対数スケール軸の設定有無)=False,
    color (色)=None,
    label (凡例ラベル)=None,
    stacked (積み上げ有無)=False,
    normed (正規化の有無)3.03.2 =None,
    *,
    data (ラベル名指定データ)=None,
    **kwargs (その他のプロパティ))
axes.Axes.hist(同上)
戻り値下記のtuple
    ・n (NumPy配列 | list( NumPy配列 ))ビンの値
    ・bins (配列形式)ビンの端
    ・patches (BarContainer | list( Polygon ) | list( object ))グラフを構成するアーティストのコンテナ

x (配列形式 | 配列形式のシーケンス)※dataデータ
bins (int | シーケンス | str)ビン指定 (ビン数・ビンの端・ビン数決定方法)
    省略:rcParams["hist.bins"] (10)
    int:ビン数 (等幅)
    シーケンス:ビンの端 (両端を含む)
    str:ビン数決定方法 (numpy.histogram_bin_edges サポートの文字列)
        'auto':自動
        'fd':フリードマン=ダイアコニス推定 (データ変動性・データサイズ・外れ値を考慮)
        'doane':スタージェス推定の改良版 (非正規データセットで適切)
        'scott':スコット推定 (データ変動性・データサイズを考慮)
        'stone':ストーン推定 (スコット推定の一般化)
        'rice':ライス推定 (データサイズのみ考慮)
        'sturges':スタージェス推定 (ガウスデータのみ最適)
        'sqrt':平方根推定 (速度と単純さで Excel 等で使用)
range (tuple | None)ビンの範囲 (bins (ビン指定)がシーケンスの場合、無効)
density (bool)正規化の有無
weights (配列形式 | None)※datax (データ)の重み (同一形式)
cumulative (bool | -1)累積の有無 (-1:逆方向に累積)
bottom (配列形式 | スカラー | None)下部位置
histtype (str)スタイル
    'bar':バー (複数データ:横並び)
    'barstacked':積み上げバー (複数データ:積み上げ)
    'step':ステップ
    'stepfilled':ステップ (塗りつぶし)
align (str)寄せ
    'left':左寄せ
    'mid':中央寄せ
    'right':右寄せ
orientation (str)バーの向き
    'vertical':垂直方向
    'horizontal':水平方向
rwidth (float | None)バーの相対幅 (histtype='step' または 'stepfilled' では無効)
    None:自動計算
log (bool)対数スケール軸の設定有無
color (color【色定義】 | 配列形式(color【色定義】) | None)
label (str | None)凡例ラベル (アンダースコアで始まるラベルは対象外)
stacked (bool)積み上げ有無
normed (bool)3.03.2正規化の有無 (density使用)
data (キーワード引数)ラベル名指定データ (※data:ラベル名指定可・詳細は、データの指定方法 参照・下記が対象)
    ・x (データ)
    ・weights (重み)
kwargs (可変長キーワード引数)patches.Patch のプロパティ

patches.Patch【パッチ】のプロパティ

親:matplotlib.artist.Artist
プロパティデフォルト設定取得備考
agg_filtercallableagg フィルター
alphaアルファ値 (0:透明 ~ 1:不透明)
animatedboolアニメーション使用の有無
antialiased
aa 3.1
bool
list( bool )
rcParams["patch.antialiased"]:Trueアンチエイリアス処理の有無
capstyleCapStyle 3.4
str
rcParams["patch.capstyle"]線端スタイル
スタイル備考
'butt'
_enums.CapStyle.butt
butt
'projecting'
_enums.CapStyle.projecting
projecting
'round'
_enums.CapStyle.round
round
clip_boxclipbox
clip_on
clip_path
color各種色 (edgecolor【外枠の色】facecolor【塗りつぶし色】)
contains 3.3callableピッカーイベント (参照:picker【ピッカーイベント】)
edgecolor
ec 3.1
color【色定義】
list( color【色定義】)
'face':塗りつぶし色
rcParams["patch.edgecolor"]:'black'外枠・塗りつぶしパターンの色
facecolor
fc 3.1
color【色定義】
list( color【色定義】)
'none'
rcParams["patch.facecolor"]:'C0'塗りつぶし色
figureFigure所属フィギュア
fillbool塗りつぶしの有無
gidstrグループId (識別子として利用可)
hatchstr塗りつぶしパターン (繰り返しで高密度 / 組合せ可)
パターン備考
'/'斜線 (左下がり)
'\'斜線 (右下がり)
'|'垂直線
'-'平行線
'+'格子
'x'斜め格子
'o' (小文字オー)円 (小)
'O' (大文字オー)円 (大)
'.' (ドット)ドット
'*'星印
in_layoutboolレイアウト計算に含めるか否か
joinstyleJoinStyle 3.4
str
rcParams["patch.joinstyle"]結合スタイル
スタイル備考
'bevel'
_enums.JoinStyle.bevel
bevel
'miter'
_enums.JoinStyle.miter
miter
'round'
_enums.JoinStyle.round
round
labelobject凡例ラベル (アンダースコアで始まるラベルは対象外)
linestyle
ls 3.1
dashes
str
(offset, on-off-seq)
上記の list
'solid'線種
スタイル備考
'-' (ダッシュ)
'solid'
solid実線
'--' (ダブルダッシュ)
'dashed'
dashed破線
'-.'
'dashdot'
dashdot一点鎖線
':' (コロン)
'dotted'
dotted点線
(offset, on-off-seq)
(offset, on-off-seq)
ユーザ定義
offset:開始位置オフセット
on-off-seq:線のありなしの対
例:二点鎖線
(0, (6.5, 1.5, 1, 1.5, 1, 1.5))
linewidth
lw 3.1
float
list( float )
rcParams["patch.linewidth"]:1.0外枠の幅
path_effectsAbstractPathEffect
pickerNone
bool
float
callable
NoneNone:ピッカーイベントなし
bool:ピッカーイベント有無
float:ピッカー有効半径
callable:ピッカーイベント hit(bool), props(dict) = picker(artist, mouseevent)
rasterizedboolラスタライズ(ビットマップ) 描画の強制有無
sketch_params
snapbool
None
スナップ (ピクセル位置補正) の有無
(Agg・MacOSX バックエンドのみサポート)
transformTransform
urllist( str )NoneハイパーリンクURL (SVG のみ対応)
visiblebool表示有無
zorderfloatZオーダー (大きい方が手前)

設定・グラフパーツ

設定・グラフパーツ の抜粋〔

pyplot.axes.Axes.その他
タイトルsuptitle【タイトル設定 (全体)】
title【タイトル設定】
set_title【タイトル設定】
get_title【タイトル取得】
Axes3D.set_title【タイトル設定】
figure.Figure.suptitle【タイトル設定 (全体)】
figure.SubFigure.suptitle
凡例legend【凡例 設定】3.5 / 3.73.8
quiverkey【ベクトルの凡例 追加】
figure.Figure.legend【凡例 設定 (全体)】3.73.8
PathCollection.legend_elements【凡例項目作成】
get_legend【凡例 取得】
get_legend_handles_labels【凡例 取得 (ハンドル・ラベル)】
軸ラベルxlabel【x軸ラベル 設定】3.3
ylabel【y軸ラベル 設定】3.3
set_xlabel【x軸ラベル 設定】3.3
set_ylabel【y軸ラベル 設定】3.3
Axes3D.set_zlabel【z軸ラベル 設定】

get_xlabel【x軸ラベル 取得】
get_ylabel【y軸ラベル 取得】
Axes3D.get_zlabel【z軸ラベル 取得】
figure.Figure.supxlabel【x軸ラベル(全体) 設定】3.43.6
figure.Figure.supylabel【y軸ラベル(全体) 設定】3.43.6
figure.SubFigure.supxlabel
figure.SubFigure.supylabel
clabel【等高線ラベル 設定】
bar_label【バーラベル】3.43.7
グリッド線grid【グリッド線 設定】3.5grid【グリッド線 設定】3.5
get_xgridlines【x軸グリッド線 取得】
get_ygridlines【y軸グリッド線 取得】
(Axes3D.grid【3Dグリッド線 取得・設定】)
Axes3D.get_zgridlines【z軸グリッド線 取得】
axis.Axis.grid【軸グリッド線 設定】3.5
axis.Axis.get_gridlines【軸グリッド線 取得】
triplot【三角形分割】
rgrids【放射状グリッド線 取得・設定】
thetagrid【放射状シータグリッド線 取得・設定】
projections.polar.PolarAxes.set_rgrids【放射状グリッド線 設定】
projections.polar.PolarAxes.set_thetagrid【放射状シータグリッド線 設定】
表示範囲xlim【x軸表示範囲 取得・設定】
ylim【y軸表示範囲 取得・設定】
axis【表示範囲等 取得・設定】3.1~3.4 / 3.7
set_xlim【x軸表示範囲 設定】3.1 / 3.6
set_ylim【y軸表示範囲 設定】3.1 / 3.6
get_xlim【x軸表示範囲 取得】
get_ylim【y軸表示範囲 取得】
axis【表示範囲等 取得・設定】3.1~3.4 / 3.7
projections.polar.PolarAxes.set_rlim【極座標範囲 設定】
Axes3D.set_xlim【3D x軸表示範囲 設定】
Axes3D.set_xlim3d【3D x軸表示範囲 設定】
Axes3D.set_ylim【3D y軸表示範囲 設定】
Axes3D.set_ylim3d【3D y軸表示範囲 設定】
Axes3D.set_zlim【3D z軸表示範囲 設定】
Axes3D.set_zlim3d【3D z軸表示範囲 設定】
Axes3D.get_xlim3d【3D x軸表示範囲 取得】
Axes3D.get_ylim3d【3D y軸表示範囲 取得】
Axes3D.get_zlim3d【3D z軸表示範囲 取得】
データ上限・下限set_xbound【x軸データ上限・下限 設定】
set_ybound【y軸データ上限・下限 設定】
get_xbound【x軸データ上限・下限 取得】
get_ybound【y軸データ上限・下限 取得】
projections.polar.PolarAxes.set_rmax【極座標上限 設定】
projections.polar.PolarAxes.set_rmin【極座標下限 設定】
目盛りxticks【x軸目盛り (ラベル) 取得・設定】3.6
yticks【y軸目盛り (ラベル) 取得・設定】3.6
locator_params【目盛り制御】
minorticks_on
minorticks_off
ticklabel_format【目盛りフォーマット設定 (指数形式)】
tick_params【目盛り・グリッド線 外観変更】
set_xticks【x軸目盛り 設定】3.2 / 3.5
set_yticks【y軸目盛り 設定】3.2 / 3.5
Axes3D.set_zticks【z軸目盛り 設定】

set_xticklabels【x軸目盛りラベル 設定】3.3 / 3.5
set_yticklabels【y軸目盛りラベル 設定】3.3 / 3.5
Axes3D.set_zticklabels【z軸目盛りラベル 設定】

get_xticks【x軸目盛り 取得】3.2
get_yticks【y軸目盛り 取得】3.2
Axes3D.get_zticks【z軸目盛り 取得】

get_xticklabels【x軸目盛りラベル 取得】3.3 / 3.6
get_yticklabels【y軸目盛りラベル 取得】3.3 / 3.6
Axes3D.get_zticklabels【z軸目盛りラベル 取得】

get_xmajorticklabels【x軸目盛りラベル 取得 (主)】3.3 / 3.6
get_ymajorticklabels【y軸目盛りラベル 取得 (主)】3.3 / 3.6
get_xminorticklabels【x軸目盛りラベル 取得 (補助)】3.3 / 3.6
get_yminorticklabels【y軸目盛りラベル 取得 (補助)】3.3 / 3.6
get_xticklines
get_yticklines
xaxis_date
yaxis_date
minorticks_on
minorticks_off
ticklabel_format【目盛りフォーマット設定 (指数形式)】
tick_params【目盛り・グリッド線 外観変更】
locator_params【目盛り制御】
fmt_xdata
fmt_ydata
ticker【目盛りモジュール】
axis.Axis.set_ticks【目盛り 設定】
axis.Axis.set_ticklabels【目盛りラベル 設定】
axis.Axis.set_tick_params【目盛り・グリッド線 外観変更】
axis.XAxis.set_ticks_position【x軸目盛り位置 設定】
axis.YAxis.set_ticks_position【y軸目盛り位置 設定】
Axes3D.locator_params【目盛り制御】

axis.Axis.set_major_formatter【フォーマッタ設定 (主)】
axis.Axis.set_minor_formatter【フォーマッタ設定 (補助)】
axis.Axis.set_major_locator【ロケータ設定 (主)】
axis.Axis.set_minor_locator【ロケータ設定 (補助)】
axis.Axis.get_ticklabels【目盛りラベル取得】
axis.Axis.get_majorticklabels【目盛りラベル取得 (主)】
axis.Axis.get_minorticklabels【目盛りラベル取得 (補助)】
axis.Axis.get_major_formatter【フォーマッタ取得 (主)】
axis.Axis.get_minor_formatter【フォーマッタ取得 (補助)】
axis.Axis.get_ticklocs
axis.Axis.get_major_locator【ロケータ取得 (主)】
axis.Axis.get_minor_locator【ロケータ取得 (補助)】
figure.Figure.autofmt_xdate【x軸日付目盛りラベル回転】
axis.Axis.get_tick_params【目盛り・グリッド線 外観取得】3.7
直線
範囲
axhline【水平線 (単一)】
axvline【垂直線 (単一)】
hlines【水平線 (複数)】3.3
vlines【垂直線 (複数)】3.3
axhspan【水平範囲】
axvspan【垂直範囲】
axline【直線】3.3

基本

import matplotlib.pyplot as plt
import numpy as np

# 初期設定
plt.rcParams['font.family'] = 'sans-serif'
plt.rcParams['font.sans-serif'] = \
    ['Yu Gothic', 'Hiragino Maru Gothic Pro', 'Noto Sans CJK JP']
fig, axs = plt.subplots(
    3, 2,
    figsize=(6, 9),
    tight_layout=True,
)
x1 = [
    1,
    2, 2,
    3, 3, 3,
    4, 4, 4, 4,
    5, 5, 5, 5, 5,
    6, 6, 6, 6,
    7, 7, 7,
    8, 8,
    9,
]
x2 = np.array(x1) + 6

# histtype='bar'
axs[0, 0].set_title('バー')
axs[0, 0].hist(
    [x1, x2],
    15,
    edgecolor='black',
    histtype='bar',
)

# histtype='barstacked'
axs[0, 1].set_title('積み上げバー')
axs[0, 1].hist(
    [x1, x2],
    15,
    edgecolor='black',
    histtype='barstacked',
)

# histtype='step'
axs[1, 0].set_title('ステップ')
axs[1, 0].hist(
    [x1, x2],
    15,
    histtype='step',
)

# histtype='stepfilled'
axs[1, 1].set_title('ステップ (塗りつぶし)')
axs[1, 1].hist(
    [x1, x2],
    15,
    histtype='stepfilled',
    alpha=0.5,
)

# orientation='horizontal'・histtype='bar'
axs[2, 0].set_title('垂直方向・バー')
axs[2, 0].hist(
    [x1, x2],
    15,
    edgecolor='black',
    histtype='bar',
    orientation='horizontal',
)

# orientation='horizontal'・histtype='stepfilled'
axs[2, 1].set_title('垂直方向・ステップ (塗りつぶし)')
axs[2, 1].hist(
    [x1, x2],
    15,
    histtype='stepfilled',
    alpha=0.5,
    orientation='horizontal',
)

# 表示
plt.show()

histのサンプル画像


積み上げ

import matplotlib.pyplot as plt
import numpy as np

# 初期設定
plt.rcParams['font.family'] = 'sans-serif'
plt.rcParams['font.sans-serif'] = \
    ['Yu Gothic', 'Hiragino Maru Gothic Pro', 'Noto Sans CJK JP']
fig, axs = plt.subplots(
    2, 2,
    figsize=(6, 6),
    tight_layout=True,
)
plt.suptitle('積み上げ')
x1 = [
    1,
    2, 2,
    3, 3, 3,
    4, 4, 4, 4,
    5, 5, 5, 5, 5,
    6, 6, 6, 6,
    7, 7, 7,
    8, 8,
    9,
]
x2 = np.array(x1) + 6

# histtype='bar'
axs[0, 0].set_title('バー')
axs[0, 0].hist(
    [x1, x2],
    15,
    edgecolor='black',
    histtype='bar',
    stacked=True,
)

# histtype='barstacked'
axs[0, 1].set_title('積み上げバー')
axs[0, 1].hist(
    [x1, x2],
    15,
    edgecolor='black',
    histtype='barstacked',
)

# histtype='step'
axs[1, 0].set_title('ステップ')
axs[1, 0].hist(
    [x1, x2],
    15,
    histtype='step',
    stacked=True,
)

# histtype='stepfilled'
axs[1, 1].set_title('ステップ (塗りつぶし)')
axs[1, 1].hist(
    [x1, x2],
    15,
    histtype='stepfilled',
    alpha=0.5,
    stacked=True,
)

# 表示
plt.show()

histのサンプル画像


累積

import matplotlib.pyplot as plt
import numpy as np

# 初期設定
plt.rcParams['font.family'] = 'sans-serif'
plt.rcParams['font.sans-serif'] = \
    ['Yu Gothic', 'Hiragino Maru Gothic Pro', 'Noto Sans CJK JP']
fig, axs = plt.subplots(
    2, 2,
    figsize=(6, 6),
    tight_layout=True,
)
plt.suptitle('累積')
x1 = [
    1,
    2, 2,
    3, 3, 3,
    4, 4, 4, 4,
    5, 5, 5, 5, 5,
    6, 6, 6, 6,
    7, 7, 7,
    8, 8,
    9,
]
x2 = np.array(x1) + 6

# histtype='bar'
axs[0, 0].set_title('バー')
axs[0, 0].hist(
    [x1, x2],
    15,
    edgecolor='black',
    histtype='bar',
    cumulative=True,
    density=True,
)

# histtype='barstacked'
axs[0, 1].set_title('積み上げバー')
axs[0, 1].hist(
    [x1, x2],
    15,
    edgecolor='black',
    histtype='barstacked',
    cumulative=True,
    density=True,
)

# histtype='step'
axs[1, 0].set_title('ステップ')
axs[1, 0].hist(
    [x1, x2],
    15,
    histtype='step',
    cumulative=True,
    density=True,
)

# histtype='stepfilled'
axs[1, 1].set_title('ステップ (塗りつぶし)')
axs[1, 1].hist(
    [x1, x2],
    15,
    histtype='stepfilled',
    alpha=0.5,
    cumulative=True,
    density=True,
)

# 表示
plt.show()

histのサンプル画像


データの指定方法

import matplotlib.pyplot as plt

# 初期設定
plt.rcParams['font.family'] = 'sans-serif'
plt.rcParams['font.sans-serif'] = \
    ['Yu Gothic', 'Hiragino Maru Gothic Pro', 'Noto Sans CJK JP']
fig, axs = plt.subplots(
    1, 2,
    figsize=(6, 3),
    tight_layout=True,
)
plt.suptitle('データ指定')
x = [
    1,
    2, 2,
    3, 3, 3,
    4, 4, 4, 4,
    5, 5, 5, 5, 5,
    6, 6, 6, 6,
    7, 7, 7,
    8, 8,
    9,
]
weights = [
    1,
    2, 2,
    1, 1, 1,
    2, 2, 2, 2,
    1, 1, 1, 1, 1,
    2, 2, 2, 2,
    1, 1, 1,
    2, 2,
    1,
]

# 通常指定
axs[0].set_title('通常指定')
axs[0].hist(
    x,
    9,
    edgecolor='black',
    weights=weights,
)

# ラベル名指定
axs[1].set_title('ラベル名指定')
axs[1].hist(
    'x',
    9,
    edgecolor='black',
    weights='weights',
    data={
        'x': x,
        'weights': weights,
    }
)

# 表示
plt.show()

histのサンプル画像


設定・グラフパーツ

import matplotlib.pyplot as plt
import numpy as np

# 初期設定
plt.rcParams['font.family'] = 'sans-serif'
plt.rcParams['font.sans-serif'] = \
    ['Yu Gothic', 'Hiragino Maru Gothic Pro', 'Noto Sans CJK JP']
fig, axs = plt.subplots(
    1, 2,
    figsize=(8, 4),
    tight_layout=True,
)
plt.suptitle('suptitle【タイトル (全体)】')

# データ
x1 = np.random.normal(-2, 3, 1000)
x2 = np.random.normal(2, 3, 1000)

# 範囲 追加
axs[0].axvspan(
    -7.5, 7.5,
    facecolor='lightgray',
    edgecolor='blue',
)
# グラフ (左)
axs[0].hist(
    x1,
    'auto',
    edgecolor='black',
    label='Data1',
)
axs[0].hist(
    x2,
    'auto',
    edgecolor='black',
    label='Data2',
)
# タイトル 設定
axs[0].set_title('title【タイトル】(左)')
# 凡例 設定
axs[0].legend(title='凡例')
# 軸ラベル 設定
axs[0].set_xlabel('xlabel【x軸ラベル】')
axs[0].set_ylabel('ylabel【y軸ラベル】')
# 表示範囲 設定
axs[0].set_ylim(0, 150)
# 目盛り 設定
axs[0].set_xticks([-15, -10, -5, 0, 5, 10, 15])
axs[0].set_yticks([0, 50, 100])
# 水平線・垂直線 追加
axs[0].axvline(0)
axs[0].axhline(50)

# グラフ (右)
axs[1].hist(
    x1,
    'auto',
    edgecolor='black',
    hatch='/',
)
axs[1].hist(
    x2,
    'auto',
    edgecolor='black',
    hatch='///',
)
# タイトル 設定
axs[1].set_title('title【タイトル】(右)')
# グリッド設定
axs[1].grid()
# データ上限・下限 設定
axs[1].set_xbound(-7.5, 7.5)
axs[1].set_ybound(25, 100)
# 目盛りラベル 設定
axs[1].set_xticks([-5, 0, 5])
axs[1].set_xticklabels(['X0', 'X1', 'X2'])
axs[1].set_yticks([25, 50, 75, 100])
axs[1].set_yticklabels(['Y0', 'Y1', 'Y2', 'Y3'])

# 表示
plt.show()

histのサンプル画像