matplotlibで積み上げ棒グラフ
2013年5月15日 2件のコメント
【やりたいこと】
外部ファイルからデータを読み込んで、matplotlibで積み上げ棒グラフを作成する。
プロット用のスクリプトをplotStack.pyとして、
カレントディレクトリに存在するstack.datをプロットする。
【サンプルコード】
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/python | |
# -*- coding: utf-8 -*- | |
import numpy as np | |
import matplotlib.pyplot as plt | |
# 外部ファイルからデータを読み込み | |
data_file = np.loadtxt("stack.dat", dtype='str') | |
# ファイルの中身【例】 | |
# A 15 7 2 | |
# B 20 5 1 | |
# C 10 3 6 | |
# 入力されたデータを[:.0]と[:,1:n-1]に分割 | |
splited_data = np.hsplit(data_file, [1]) | |
# 1次元にリシェイプ | |
methods = splited_data[0].flatten() | |
# 切り取られた中身【例】 | |
# A B C | |
# Stringではなくfloatにキャスト | |
data = splited_data[1].astype(np.float) | |
# 切り取られた中身【例】 | |
# 15.0 7.0 2.0 | |
# 20.0 5.0 1.0 | |
# 10.0 3.0 6.0 | |
# バーがの描画されるポイント(x軸方向) | |
ind = np.arange(len(data)) | |
# バーの横幅 | |
width = 0.35 | |
# 色を変えられるように設定 | |
colors = ['r', 'g', 'b', 'c'] | |
label = ['bottom', 'middle', 'top'] | |
bottom=np.zeros(data.shape[0]) | |
# packet.datの4列目が邪魔 | |
for i in range(data.shape[1]): | |
plt.bar(ind, # バーの左端と重なるx座標 | |
data[:,i], # バーの高さ | |
width, # バーの幅 | |
bottom, # バーが始まる高さ | |
color=colors[i], # 色 | |
label=label[i] # 凡例用のラベル | |
) | |
# 「積み上げ」を表現するための足場 | |
bottom += data[:,i] | |
# xtics(labelの位置, label), labelは1次元配列 | |
plt.xticks(ind+width/2., methods ) | |
# 左右の余白 | |
margin = 0.25 | |
# 余白を加味したx軸方向の変域 | |
plt.xlim(-margin, len(data)-1+width+margin) | |
# Y軸ラベル | |
plt.ylabel('Y label') | |
# 凡例を表示 | |
plt.legend(loc="upper right") | |
# グリッドを表示 | |
plt.grid(True) | |
# 画像として保存 | |
plt.savefig("GraphStack.png") | |
# 確認用描画 | |
#plt.show() |
【データファイル】
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
A 15 7 2 | |
B 20 5 1 | |
C 10 3 6 |
【保存された画像】
ピンバック: matplotlibで棒グラフ(横に並べる) | mkacky
ピンバック: Pythonで積み上げ棒グラフを並べてみる | IT技術情報局