Skip to content

Instantly share code, notes, and snippets.

Last active March 19, 2018 10:41
Show Gist options
  • Save olbat/dc8657d22b7180329afef44553543085 to your computer and use it in GitHub Desktop.
Save olbat/dc8657d22b7180329afef44553543085 to your computer and use it in GitHub Desktop.
Python3 matplotlib script that plots histograms with data from text files (one number per line)
usage: {} title data.txt [data2.txt ...] > histogram.png
import sys
import math
import os.path
import matplotlib
import matplotlib.pyplot as plt # noqa: F401
# display help if bad arguments
if len(sys.argv) < 3:
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()
for axis in axislist:
plt.savefig(sys.stdout.buffer, format="png")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment