diff --git a/pyerrors/misc.py b/pyerrors/misc.py index 0cd95f86..962b91c5 100644 --- a/pyerrors/misc.py +++ b/pyerrors/misc.py @@ -1,8 +1,40 @@ import pickle import numpy as np +import matplotlib.pyplot as plt from .obs import Obs +def errorbar(x, y, axes=plt, **kwargs): + """pyerrors wrapper for the errorbars method of matplotlib + + Parameters + ---------- + x : list + A list of x-values which can be Obs. + y : list + A list of y-values which can be Obs. + axes : (matplotlib.pyplot.axes) + The axes to plot on. default is plt. + """ + val = {} + err = {} + for name, comp in zip(["x", "y"], [x, y]): + if all(isinstance(o, Obs) for o in comp): + if not all(hasattr(o, 'e_dvalue') for o in comp): + [o.gamma_method() for o in comp] + val[name] = [o.value for o in comp] + err[name] = [o.dvalue for o in comp] + else: + val[name] = comp + err[name] = None + + if f"{name}err" in kwargs: + err[name] = kwargs.get(f"{name}err") + kwargs.pop(f"{name}err", None) + + axes.errorbar(val["x"], val["y"], xerr=err["x"], yerr=err["y"], **kwargs) + + def dump_object(obj, name, **kwargs): """Dump object into pickle file. diff --git a/tests/misc_test.py b/tests/misc_test.py new file mode 100644 index 00000000..3211a806 --- /dev/null +++ b/tests/misc_test.py @@ -0,0 +1,20 @@ +import numpy as np +import matplotlib.pyplot as plt +import pyerrors as pe +import pytest + + +def test_obs_errorbar(): + x_float = np.arange(5) + x_obs = [] + y_obs = [] + for x in x_float: + x_obs.append(pe.pseudo_Obs(x, 0.1, "test")) + y_obs.append(pe.pseudo_Obs(x ** 2, 0.1, "test")) + + for xerr in [2, None]: + for yerr in [0.1, None]: + pe.errorbar(x_float, y_obs, marker="x", ms=2, xerr=xerr, yerr=yerr) + pe.errorbar(x_obs, y_obs, marker="x", ms=2, xerr=xerr, yerr=yerr) + + plt.close('all')