Skip to content

Instantly share code, notes, and snippets.

@mkacky
Created June 10, 2014 14:22
Show Gist options
  • Save mkacky/4170cc64291f6062bbf0 to your computer and use it in GitHub Desktop.
Save mkacky/4170cc64291f6062bbf0 to your computer and use it in GitHub Desktop.
#! /usr/bin/python
# -*- coding: utf-8 -*-
import sys
import numpy as np
import matplotlib.pyplot as plt
data = np.loadtxt("data.dat")
## 中身の例
## 4種類の値(4つの尺度)をもつサンプルを3つ分(1行=1データ)。
## 例えば、あるグループ(1行=1サンプル)内に同じ血液型(尺度、4種類)の人間が何人ずついるか。
# 15 7 2 6
# 20 5 1 3
# 10 3 6 4
num_sample = data.shape[0]
num_item_per_sample = data.shape[1]
## 凡例用のラベル(サンプル数だけ必要)
legend_labels = ["A", "B", "C"]
## 凡例の数だけ色を用意する
colors = ["red", "green", "blue"]
## 棒グラフの幅
width = 0.25
## 余白
margin = 0.2
## 1尺度あたりのデータを並べるのに必要な幅。
block = width * num_sample + margin
## 棒グラフ(長方形)の左下の位置の基準にするポイント
ind = np.arange(num_item_per_sample) * block
## 各サンプルについて、棒グラフを描画する
for i in range(num_sample):
plt.bar(
ind + width*i, ## 棒グラフの左下の点の座標。データ毎に少しずつズラす
data[i], ## 各始点にプロットされる1次元配列
width, ## 棒の幅
color=colors[i], ## 棒の色
label=legend_labels[i] ## 棒の凡例名
)
## x軸に表示するラベルを設定する
xlabels = ["1st", "2nd", "3rd", "4th"]
##x軸にラベルを表示する位置を設定する。
xlocs = ind + width * num_sample / 2.
## xtics(labelの位置, label), labelは1次元配列
plt.xticks(xlocs, xlabels )
## 余白を加味したx軸方向の変域
plt.xlim(-margin, ind[-1]+width*num_sample+margin)
## Y軸ラベル
plt.ylabel('y-label')
## 凡例を表示
plt.legend(prop={'size' : 18},loc="upper right")
## グリッドを表示
plt.grid(True)
## 画像として保存
plt.savefig("bar.png", bbox_inches="tight")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment