Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
matplotlibのbar関数のwapper
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
def bars(target, size, labels=None, width=0.25, margin=0.5,
output=None,title=None, xlabel=None, ylabel=None, loc="best"):
"""
plot bars
required args
--------------
target: type dict,key:label,value:points(array)
size: type int, number of points
optional args
---------------
labels: type array, group label
width: type float, bar's width
margin: type float, length between bars
output: type str,output file name
title: type str, title name
xlabel: type str, xlabel name
ylabel: type str, ylabel name
loc: type str, legend location
"""
block = len(target) * width + margin
ind = np.arange(size) * block
index = 0
for l, points in target.iteritems():
plt.bar(ind + width * index,
points, width,
color=cm.cool(float(index) / len(target)),
label=l)
index += 1
# centring
plt.xlim(-margin, ind[-1] + width*len(target)+margin)
if title:
plt.title(title)
if xlabel:
plt.xlabel(xlabel)
if ylabel:
plt.ylabel(ylabel)
if labels:
plt.xticks(ind+(len(target)/2)*width, labels)
plt.legend(loc=loc)
# draw bars
if output:
plt.savefig(output)
else:
plt.show()
def main():
x1 = np.random.random(5)
x2 = np.random.random(5)
test = {"x1":x1, "x2":x2}
labels = ["A", "B", "C", "D", "E"]
bars(test, len(x1), output="output", labels=labels, xlabel="hoge", ylabel="fuga", title="test")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment