Skip to content

Instantly share code, notes, and snippets.

@olbat olbat/plot-histograms.py
Last active Mar 19, 2018

Embed
What would you like to do?
Python3 matplotlib script that plots histograms with data from text files (one number per line)
#!/usr/bin/python3
"""
usage: {} title data.txt [data2.txt ...] > histogram.png
"""
import sys
import math
import os.path
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt # noqa: F401
# display help if bad arguments
if len(sys.argv) < 3:
print(__doc__.format(sys.argv[0]))
sys.exit(1)
n = len(sys.argv) - 2
m = math.ceil(math.sqrt(n))
plotsize = (m, math.ceil(n / m))
fig = plt.figure(figsize=(4 * plotsize[1], 2.5 * plotsize[0]))
tle = fig.suptitle(sys.argv[1], fontsize=18, x=0.001, y=0.999,
horizontalalignment='left', verticalalignment='top',
bbox=dict(facecolor='none', edgecolor='black', pad=2))
plt.rcParams["axes.grid"] = True
plt.rcParams["grid.linestyle"] = "dotted"
maxylim = None
axislist = []
for i, filename in enumerate(sys.argv[2:]):
pos = (i // plotsize[1], i % plotsize[1])
axis = plt.subplot2grid(plotsize, pos)
plt.title(os.path.basename(filename).split('.', 2)[0])
with open(filename, 'r') as f:
values = [float(l.strip()) for l in f.readlines()]
su = sum(values)
mean = round(su / len(values), 3)
med = round(sorted(values)[len(values)//2], 3)
su = round(su, 2)
plt.xlabel("Values [mean:{},med:{},sum:{}]".format(mean, med, su))
plt.ylabel("Count [total:{}]".format(len(values)))
ys, xs, _ = plt.hist(values) # , normed=True)
for j, y in enumerate(ys):
plt.text(xs[j], ys[j], str(int(ys[j])))
if maxylim is None or axis.get_ylim() > maxylim:
maxylim = axis.get_ylim()
axislist.append(axis)
for axis in axislist:
axis.set_ylim(maxylim)
plt.tight_layout()
plt.savefig(sys.stdout.buffer, format="png")
plt.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.