Skip to content

Instantly share code, notes, and snippets.

@saiias
Created January 15, 2015 14:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saiias/314f0e694e7ddb2cf305 to your computer and use it in GitHub Desktop.
Save saiias/314f0e694e7ddb2cf305 to your computer and use it in GitHub Desktop.
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