唯物是真 @Scaled_Wurm

プログラミング(主にPython2.7)とか機械学習とか

matplotlibで積み上げ棒グラフ

積み上げ棒グラフ(stacked bar chart)は、棒グラフを積み重ねた以下のような形のグラフです
matplotlibのbar関数ではオフセットを指定できるので、オフセットを足しながら棒グラフをかいていけば積み上げ棒グラフができます
f:id:sucrose:20130723010745p:plain

from pylab import *

def bar_stacked(data, colors, labels, ticks):
    offset = zeros(data.shape[0])
    for i in xrange(data.shape[1]):
        bar(range(data.shape[0]), data[:, i], 0.8, offset, align='center', color=colors[i], label=labels[i])
        offset += data[:, i]
    
    xticks(range(data.shape[0]), ticks)

data = arange(9).reshape(3, 3)
#array([[0, 1, 2],
#       [3, 4, 5],
#       [6, 7, 8]]

bar_stacked(data, 'rgb', 'abc', 'xyz')
legend()
show()


横向きの棒グラフにするときには barh 関数を使えばいいです
f:id:sucrose:20130723010809p:plain

from pylab import *

def barh_stacked(data, colors, labels, ticks):
    offset = zeros(data.shape[0])
    for i in xrange(data.shape[1]):
        barh(range(data.shape[0]), data[:, i], 0.8, offset, align='center', color=colors[i], label=labels[i])
        offset += data[:, i]
    
    yticks(range(data.shape[0]), ticks)

data = arange(9).reshape(3, 3)
#array([[0, 1, 2],
#       [3, 4, 5],
#       [6, 7, 8]]

barh_stacked(data, 'rgb', 'abc', 'xyz')
legend()
show()

ちなみに積み上げるのではなく、棒を複数まとめて並べたいときには、以下のデモのように少しずつ位置をずらしながら表示させればできます