Coverage for src/km3pipe/plot.py: 42%
66 statements
« prev ^ index » next coverage.py v7.5.1, created at 2024-05-08 03:14 +0000
« prev ^ index » next coverage.py v7.5.1, created at 2024-05-08 03:14 +0000
1# Filename: plot.py
2# pylint: disable=C0103
3# pragma: no cover
4"""
5Common Plotting utils.
6"""
7try:
8 import _tkinter # noqa
9except ImportError:
10 import matplotlib
12 matplotlib.use("agg")
13import matplotlib.pyplot as plt
14import numpy as np
16import km3pipe.extras
18__author__ = "Moritz Lotze"
19__copyright__ = "Copyright 2018, Tamas Gal and the KM3NeT collaboration."
20__credits__ = []
21__license__ = "BSD-3"
22__maintainer__ = "Moritz Lotze"
23__email__ = "mlotze@km3net.de"
24__status__ = "Development"
27def get_ax(ax=None):
28 """Grab last ax if none specified, or pass through."""
29 if ax is None:
30 ax = plt.gca()
31 return ax
34def diag(ax=None, linecolor="0.0", linestyle="--", **kwargs):
35 """Plot the diagonal."""
36 ax = get_ax(ax)
37 xy_min = np.min((ax.get_xlim(), ax.get_ylim()))
38 xy_max = np.max((ax.get_ylim(), ax.get_xlim()))
39 return ax.plot(
40 [xy_min, xy_max], [xy_min, xy_max], ls=linestyle, c=linecolor, **kwargs
41 )
44def automeshgrid(
45 x, y, step=0.02, xstep=None, ystep=None, pad=0.5, xpad=None, ypad=None
46):
47 """Make a meshgrid, inferred from data."""
48 if xpad is None:
49 xpad = pad
50 if xstep is None:
51 xstep = step
52 if ypad is None:
53 ypad = pad
54 if ystep is None:
55 ystep = step
56 xmin = x.min() - xpad
57 xmax = x.max() + xpad
58 ymin = y.min() - ypad
59 ymax = y.max() + ypad
60 return meshgrid(xmin, xmax, step, ymin, ymax, ystep)
63def meshgrid(x_min, x_max, x_step, y_min=None, y_max=None, y_step=None):
64 """Make a meshgrid, e.g. when plotting decision surfaces."""
65 if y_min is None:
66 y_min = x_min
67 if y_max is None:
68 y_max = x_max
69 if y_step is None:
70 y_step = x_step
71 xx, yy = np.meshgrid(
72 np.arange(x_min, x_max, x_step), np.arange(y_min, y_max, y_step)
73 )
74 return xx, yy
77def bincenters(bins):
78 """Bincenters, assuming they are all equally spaced."""
79 bins = np.atleast_1d(bins)
80 return 0.5 * (bins[1:] + bins[:-1])
83def prebinned_hist(counts, binlims, ax=None, *args, **kwargs):
84 """Plot a histogram with counts, binlims already given.
86 Examples
87 ========
88 >>> gaus = np.random.normal(size=100)
89 >>> counts, binlims = np.histogram(gaus, bins='auto')
90 >>> prebinned_hist(countsl binlims)
91 """
92 ax = get_ax(ax)
93 x = bincenters(binlims)
94 weights = counts
95 return ax.hist(x, bins=binlims, weights=weights, *args, **kwargs)
98def plot_convexhull(xy, ax=None, plot_points=True):
99 scipy = km3pipe.extras.scipy()
100 from scipy.spatial import ConvexHull
102 ch = ConvexHull(xy)
103 ax = get_ax(ax)
104 if plot_points:
105 ax.plot(xy[:, 0], xy[:, 1], "o")
106 for simplex in ch.simplices:
107 ax.plot(xy[simplex, 0], xy[simplex, 1], "k-")
108 return ax