Skip to content

Instantly share code, notes, and snippets.

@mkacky
Last active December 20, 2015 07:59
Show Gist options
  • Save mkacky/6097561 to your computer and use it in GitHub Desktop.
Save mkacky/6097561 to your computer and use it in GitHub Desktop.
sample of annotate()
#! /usr/bin/python
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
# 全体のフォントサイズを設定
plt.rcParams.update({'font.size':15})
####################
### 入力データを加工
data_file = np.loadtxt("stack.dat", dtype='str')
#print data_file
## 例
# A 15 7 2
# B 20 5 1
# C 10 3 6
splited_data = np.hsplit(data_file, [1])
#print splited_data
## 例
# 15 7 2
# 20 5 1
# 10 3 6
# Stringではなくfloatにキャスト
data = splited_data[1].astype(np.float)
#print data
## 例
# 15. 7. 2.
# 20. 5. 1.
# 10. 3. 6.
####################
### グラフ作成用準備
# バーがの描画されるポイント(x軸方向)
ind = np.arange(len(data)) # the x locations for the groups
# バーの横幅
width = 0.35 # the width of the bars: can also be len(x) sequence
# 色を変えられるように設定
colors = ['r', 'g', 'b', 'c']
# legend用のラベルを準備
labels = data_file[:,0]
## 例
# A
# B
# C
# annotate用に利用中のAxesオブジェクトを取得
ax = plt.gca()
# 積み上げ用の一時記憶
bottom=np.zeros(data.shape[0])
# 棒グラフを作成
for i in range(data.shape[1]):
plt.bar(ind,
data[:,i],
width,
bottom,
color=colors[i],
label=labels[i]
)
for j in range(len(data)):
ann = ax.annotate(str(data[j,i]), xy=(ind[j]+width/3, bottom[j]+data[j,i]*0.45),fontsize=12)
bottom += data[:,i]
####################
### グラフ周りの調整
# グリッドを表示
plt.grid(True)
# Y軸ラベル
plt.ylabel('Y Label')
# xtics(ラベルの位置, ラベル), ラベルは1次元配列
plt.xticks(ind+width/2., data_file[:,0])
# 左右の余白
margin = 0.25
# 余白を加味したx軸方向の変域
plt.xlim(-margin, len(data)-1+width+margin)
## 凡例の調整
# 凡例をいじるための準備
handles, labels = ax.get_legend_handles_labels()
#print handles # 線やマーカーを含んだオブジェクト
#print labels # 凡例に表示されるラベル
# 凡例表示(逆順)
plt.legend(handles[::-1], labels[::-1], loc="upper right")
# 画像を保存
plt.savefig("GraphPacket.png")
# 確認用描画
#plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment