Commit b0499348 authored by Daniel Armbruster's avatar Daniel Armbruster Committed by thomas.forbriger
Browse files

plotting of multiple files to one figure provided; legend provided

This is a legacy commit from before 2015-03-01.
It may be incomplete as well as inconsistent.
See COPYING.legacy and README.history for details.


SVN Path:     http://gpitrsvn.gpi.uni-karlsruhe.de/repos/TFSoftware/trunk
SVN Revision: 4704
SVN UUID:     67feda4a-a26e-11df-9d6e-31afc202ad0c
parent a974b6f5
......@@ -31,14 +31,11 @@
# REVISIONS and CHANGES
# 08/02/2012 V0.1 Daniel Armbruster
# 04/05/2012 V0.2 Stable for TFSoftware.
# 12/05/2012 V0.3 Plot multiple datafiles; provide legend
#
# =============================================================================
"""
Plot an simple power spectrum using python's matplotlib.
TODO:
* legend not supported yet
* plot multiple datafiles
"""
import sys
......@@ -48,7 +45,7 @@ import string
import matplotlib
import matplotlib.pyplot as plt
__version__ = "V0.2"
__version__ = "V0.3"
__subversion__ = "$Id: pspecplot.py 616 2012-05-05 00:03:30Z uhcnl $"
__license__ = "GPLv2"
__author__ = "Daniel Armbruster"
......@@ -71,8 +68,8 @@ class Usage(Error):
Usage: pspecplot [-v|--verbose] [--overwrite] [--oformat arg] [--outbase arg]
[-t|--title arg] [--orientation arg] [--nologlog] [-g|--grid]
[--xlabel arg] [--ylabel arg] [--xlim val:val]
[--ylim val:val]
DATAFILE
[--ylim val:val] [--legend arg] [--legpos arg]
DATAFILE [DATAFILE [...]]
or: pspecplot -h|--help"""
if 0 != len(self.msg):
sys.stderr.write("pspecplot: " + self.msg + "\n")
......@@ -108,8 +105,20 @@ def help():
--ylim val:val Set fixed y-limits of the current axis.
--nologlog Disable loglog scale of axis
--fit Fit plot to page (only is saving plot to file).
DATAFILE File which contain the data (two columns).\n"""
--legend arg Specify legend arguments.
arg is a list of whitespace separated strings. If it
isn't desired to print the legend for a specific spectrum
just pass '--'. By default plotting a legend is enabled.
To disable a legend use the '--legpos' commandline
argument. Additionally the legend position can be
specified using the '--legpos' commandline argument.
--legpos arg Set legend position or disable legend.
Valid arguments are 'unset' to disable legend, 'best',
'upper right' (default), 'upper left', 'lower left',
'lower right', 'right', 'center left', 'center right',
'lower center', 'upper center' and 'center'.
DATAFILE(s) File(s) which contain(s) the data (two columns).\n"""
Usage().display()
sys.stdout.write(help_text)
......@@ -121,7 +130,8 @@ def main(argv=None):
try:
opts, args = getopt.getopt(argv[1:], "hvgt:", ["help", "verbose", \
"overwrite", "title=", "orientation=", "outbase=", "oformat=", \
"xlabel=", "ylabel=", "nologlog", "grid", "fit", "xlim=", "ylim="])
"xlabel=", "ylabel=", "nologlog", "grid", "fit", "xlim=", "ylim=", \
"legend=", "legpos="])
except getopt.GetoptError as err:
raise Usage(err.msg)
# fetch arguments
......@@ -138,6 +148,8 @@ def main(argv=None):
fit = None
xlim = []
ylim = []
legargs = args
legpos = 'upper right'
for opt, arg in opts:
if opt in ("-v", "--verbose"):
......@@ -151,7 +163,7 @@ def main(argv=None):
oformat = arg
elif opt in ("--orientation"):
orientation = arg
if orientation != "portrait" or orientation != "landscape":
if orientation not in ("portrait", "landscape"):
raise Usage("Invalid 'orientation' argument.")
elif opt in ("--outbase"):
outbase = arg
......@@ -181,11 +193,15 @@ def main(argv=None):
raise
except:
raise Usage("Invalid 'ylim' argument.")
elif opt in ("--legend"):
legargs = arg.split()
elif opt in ("--legpos"):
legpos = arg
else:
raise Usage("Unhandled option chosen.")
if 1 == len(args):
datafile = args[0]
if len(args) >= 1:
pass
else:
raise Usage("Invalid arguments.")
......@@ -193,49 +209,79 @@ def main(argv=None):
and not overwrite:
raise Usage(outbase+"."+string.lower(oformat)+" already exists.")
# read data from datafile
if not os.access(datafile, os.F_OK):
raise Error("Invalid path to DATAFILE.")
if 0 == os.stat(datafile).st_size:
raise Error("Given DATAFILE is an empty file.")
if verbose:
sys.stdout.write("pspecplot: Reading DATAFILE ... \n")
try:
x = []
y = []
file = open(datafile, 'r')
for line in file:
col1,col2 = line.split()
x.append(col1)
y.append(col2)
except IOError as err:
raise Error("[Errno "+str(err.errno)+"] "+err.strerror+": "+err.filename)
else:
file.close()
# check data consistency
if len(x) != len(y):
raise Error("Data not consistent.")
# save data in 2D lists
x_coords = []
y_coords = []
# read data from datafiles
for datafile in args:
if not os.access(datafile, os.F_OK):
raise Error("Invalid path to file '{0}'.".format(datafile))
if 0 == os.stat(datafile).st_size:
raise Error("Given DATAFILE '{0}' is an empty file.".format(datafile))
if verbose:
sys.stdout.write( \
"pspecplot: Reading file '{0}' ... \n".format(datafile))
try:
x = []
y = []
file = open(datafile, 'r')
for line in file:
col1,col2 = line.split()
x.append(col1)
y.append(col2)
except IOError as err:
raise Error( \
"[Errno "+str(err.errno)+"] "+err.strerror+": "+err.filename)
else:
file.close()
# check data consistency
if len(x) == len(y):
x_coords.append(x)
y_coords.append(y)
else:
raise Error( \
"Data not consistent in file '{0}' not consistent.".format(datafile))
# generate plot
if verbose:
sys.stdout.write("pspecplot: Preparing plot ... \n")
fig = plt.figure()
ax = fig.add_subplot(111)
# x and y limits
if 2 == len(xlim):
plt.xlim(xlim[0], xlim[1])
if 2 == len(ylim):
plt.ylim(ylim[0], ylim[1])
plt.plot(x, y)
# plot data
legend_handlers = []
for x, y in zip(x_coords, y_coords):
legend_handlers.append(tuple(plt.plot(x, y)))
# remove handlers where printing the legend isn't desired
indices = [i for i, x in enumerate(legargs) if "--" == x]
for i in indices:
del legend_handlers[i]
del legargs[i]
plt.grid(grid)
if not nologlog:
plt.loglog()
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.title(plotTitle)
# legend specific
if 'unset' != legpos:
try:
sys.stdout.write("pspecplot: Plotting legend ...\n")
ax.legend(legend_handlers, legargs, legpos)
except:
raise Error("While plotting legend.")
if len(outbase):
if verbose:
sys.stdout.write("pspecplot: Saving file ... \n")
sys.stdout.write( \
"pspecplot: Saving plot to file '{0}' ... \n".format( \
outbase+"."+string.lower(oformat)))
try:
plt.savefig(outbase+"."+string.lower(oformat), \
orientation=orientation, format=oformat, bbox_inches=fit)
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment