• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

APN-Pucky / smpl / 15279598337

27 May 2025 03:36PM UTC coverage: 88.914% (-0.06%) from 88.971%
15279598337

push

github

APN-Pucky
fix: linstyle

2 of 3 new or added lines in 1 file covered. (66.67%)

1564 of 1759 relevant lines covered (88.91%)

4.44 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

93.52
/smpl/plot.py
1
"""Simplified plotting."""
2

3
import matplotlib
5✔
4
import matplotlib.pyplot as plt
5✔
5
import numpy as np
5✔
6
import smplr
5✔
7
import sympy
5✔
8
import uncertainties
5✔
9
import uncertainties.unumpy as unp
5✔
10
from matplotlib import pylab
5✔
11
from matplotlib.pyplot import *
5✔
12

13
# local imports
14
from smpl import doc, interpolate, io, stat, util, wrap
5✔
15
from smpl import fit as ffit
5✔
16

17

18
def set_plot_style():
5✔
19
    # fig_size = (8, 6)
20
    # fig_legendsize = 14
21
    # fig_labelsize = 12 # ‘xx-small’, ‘x-small’, ‘small’, ‘medium’, ‘large’, ‘x-large’, ‘xx-large’.
22
    params = {
×
23
        "legend.fontsize": "x-large",
24
        "figure.figsize": (8, 6),
25
        "axes.labelsize": "x-large",
26
        "axes.titlesize": "x-large",
27
        "xtick.labelsize": "x-large",
28
        "ytick.labelsize": "x-large",
29
    }
30
    pylab.rcParams.update(params)
×
31
    matplotlib.rcParams.update(params)
×
32
    # matplotlib.rcParams.update({'font.size': fig_labelsize})
33
    # colors = dict(mcolors.BASE_COLORS, **mcolors.CSS4_COLORS)
34

35

36
unv = unp.nominal_values
5✔
37
usd = unp.std_devs
5✔
38

39
default = {
5✔
40
    #    'params'        :[None      ,"Initial fit parameters",
41
    "title": [None, "Plot title"],
42
    "xlabel": [
43
        "",
44
        "X axis label",
45
    ],
46
    "ylabel": [
47
        "",
48
        "Y axis label",
49
    ],
50
    "label": [
51
        None,
52
        "Legend name of plotted ``data``",
53
    ],
54
    "fmt": [
55
        ".",
56
        "Format for plotting fit function (could be a line style, marker or a combination of both or 'step')",
57
    ],
58
    "where": [
59
        "mid",
60
        "Where to place the ticks. Possible values are 'pre', 'post', 'mid', 'edge'. Might be incompatible with uncertainties.",
61
    ],
62
    "units": [
63
        None,
64
        "Units of the fit parameters as strings. Displayed in the Legend",
65
    ],
66
    "save": [
67
        None,
68
        " File to save the plot",
69
    ],
70
    "lpos": [
71
        0,
72
        "Legend position",
73
    ],
74
    "tight": [
75
        True,
76
        "tight_layout",
77
    ],
78
    #          'frange'        :[None      ,"Limit the fit to given range. First integer is the lowest and second the highest index.",],
79
    "prange": [
80
        None,
81
        "Limit the plot of the fit to given range",
82
    ],
83
    "sigmas": [
84
        0,
85
        "Color the array of given ``sigma`` times uncertainty. Only works if the fit function is coded with ``unp``",
86
    ],
87
    "data_sigmas": [
88
        1,
89
        "Color the array of given ``sigma`` times uncertainty. Only works if the data has uncertainties",
90
    ],
91
    "init": [False, "Initialize a new plot"],
92
    "ss": [
93
        True,
94
        "save, add legends and grid to the plot",
95
    ],
96
    "also_data": [True, " also plot the data"],
97
    "also_fit": [
98
        True,
99
        "also plot the fit",
100
    ],
101
    "auto_fit": [
102
        False,
103
        "automatically fit",
104
    ],
105
    "logy": [
106
        False,
107
        "logarithmic x axis",
108
    ],
109
    "logx": [
110
        False,
111
        "logarithmic y axis",
112
    ],
113
    "function_color": [
114
        None,
115
        "Color of the function plot",
116
    ],
117
    "data_color": [
118
        None,
119
        "Color of the data plot",
120
    ],
121
    "fit_color": [
122
        None,
123
        "Color of the fit plot",
124
    ],
125
    "fit_fmt": [
126
        "-",
127
        "Format of the fit plot",
128
    ],
129
    "residue": [
130
        False,
131
        "Display difference between fit and data in a second plot",
132
    ],
133
    "residue_err": [
134
        True,
135
        "Differences between fit and data will have errorbars",
136
    ],
137
    "show": [
138
        False,
139
        "Call plt.show()",
140
    ],
141
    "size": [
142
        None,
143
        "Size of the plot as a tuple (x,y). Only has an effect if ``init`` is True",
144
    ],
145
    "number_format": [
146
        io.gf(4),
147
        "Format to display numbers.",
148
    ],
149
    # ,          'selector'      :[ None     ,"Function that takes ``x`` and ``y`` as parameters and returns an array mask in order to limit the data points for fitting. Alternatively a mask for selecting elements from datax and datay.",],
150
    # ,          'fixed_params'  :[ True     ,"Enable fixing parameters by choosing the same-named variables from ``kwargs``.",],
151
    # ,          'sortbyx'       :[ True     , "Enable sorting the x and y data so that x is sorted.",],
152
    "interpolate": [False, "Enable interpolation of the data."],
153
    "interpolate_fmt": [
154
        "-",
155
        "Either format string or linestyle tuple.",
156
    ],
157
    "interpolate_label": [
158
        None,
159
        "Label for the interpolation.",
160
    ],
161
    "extrapolate": [
162
        True,
163
        "Enable extrapolation of whole data if fit range is limited by ``frange`` or ``fselector``.",
164
    ],
165
    "extrapolate_min": [
166
        None,
167
        "Lower extrapolation bound",
168
    ],
169
    "extrapolate_max": [
170
        None,
171
        "Higher extrapolation bound",
172
    ],
173
    "extrapolate_fmt": [
174
        "--",
175
        "Format of the extrapolation line",
176
    ],
177
    "extrapolate_hatch": [
178
        r"||",
179
        "Extrapolation shape/hatch for filled area in case of ``sigmas``>0. See https://matplotlib.org/stable/gallery/shapes_and_collections/hatch_style_reference.html",
180
    ],
181
    "bbox_to_anchor": [
182
        None,
183
        "Position in a tuple (x,y),Shift position of the legend out of the main pane. ",
184
    ],
185
    "ncol": [
186
        None,
187
        "Columns in the legend if used with ``bbox_to_anchor``.",
188
    ],
189
    "steps": [
190
        1000,
191
        "resolution of the plotted function",
192
    ],
193
    "fitinline": [
194
        False,
195
        "No newlines for each fit parameter",
196
    ],
197
    "grid": [
198
        True,
199
        "Enable grid for the plot",
200
    ],
201
    "hist": [
202
        False,
203
        "Enable histogram plot",
204
    ],
205
    "stairs": [
206
        False,
207
        "Enable stair plot",
208
    ],
209
    "capsize": [5, "size of cap on error bar plot"],
210
    "axes": [None, "set current axis"],
211
    "linestyle": [None, "linestyle, only active if `fmt`=None"],
212
    "xspace": [
213
        np.linspace,
214
        "xspace gets called with xspace(xmin,xmax,steps) in :func:`function` to get the points of the function that will be drawn.",
215
    ],
216
    "alpha": [0.2, "alpha value for the fill_between plot"],
217
}
218

219

220
@doc.append_doc(ffit.fit_kwargs)
5✔
221
@doc.append_str("\t")
5✔
222
@doc.append_str(doc.array_table(default, init=False))
5✔
223
@doc.append_str(
5✔
224
    doc.array_table({"plot_kwargs        ": ["default", "description"]}, bottom=False)
225
)
226
@doc.append_str("\n\n")
5✔
227
def plot_kwargs(kwargs):
5✔
228
    """Set default :func:`plot_kwargs` if not set."""
229
    kwargs = ffit.fit_kwargs(kwargs)
5✔
230
    for k, v in default.items():
5✔
231
        if k not in kwargs:
5✔
232
            kwargs[k] = v[0]
5✔
233
    return kwargs
5✔
234

235

236
# TODO optimize to minimize number of calls to function
237
# @append_doc(default_kwargs)
238

239

240
def fit(func, *adata, **kwargs):
5✔
241
    """
242
    Fit and plot function to datax and datay.
243

244
    Parameters
245
    ----------
246
    datax : array_like
247
        X data either as ``unp.uarray`` or ``np.array`` or ``list``
248
    datay : array_like
249
        Y data either as ``unp.uarray`` or ``np.array`` or ``list``
250
    function : func
251
        Fit function with parameters: ``x``, ``params``
252
    **kwargs : optional
253
        see :func:`plot_kwargs`.
254
    Fit parameters can be fixed via ``kwargs`` eg. ``a=5``.
255

256
    Returns
257
    -------
258
    array_like
259
        Optimized fit parameters of ``function`` to ``datax`` and ``datay``.
260
        If ``datay`` is complex, both the real and imaginary part are returned.
261

262
    Examples
263
    --------
264

265
    .. plot::
266
        :include-source:
267

268
        >>> from smpl import functions as f
269
        >>> from smpl import plot
270
        >>> param = plot.fit([0,1,2],[0,1,2],f.line)
271
        >>> float(plot.unv(param).round()[0])
272
        1.0
273

274
    """
275
    function = func
5✔
276
    if "function" in kwargs:
5✔
277
        function = kwargs["function"]
5✔
278
        del kwargs["function"]
5✔
279
        adata = [func, *adata]
5✔
280
    # Fix parameter order if necessary
281
    elif isinstance(function, (list, tuple, np.ndarray)):
5✔
282
        adata = [adata[-1], function, *adata[:-1]]
5✔
283
        function = adata[0]
5✔
284
        adata = adata[1:]
5✔
285
    if util.true("bins", kwargs):
5✔
286
        # yvalue will be overwritten
287
        ndata = [*adata, *adata]
5✔
288
        for i, o in enumerate(adata):
5✔
289
            ndata[2 * i] = o
5✔
290
            ndata[2 * i + 1] = o * 0
5✔
291
        adata = ndata
5✔
292

293
    assert len(adata) % 2 == 0, "data must be pairs of x and y data"
5✔
294
    if len(adata) == 2:
5✔
295
        datax, datay = adata
5✔
296
    else:
297
        rs = []
5✔
298
        for i in range(0, len(adata), 2):
5✔
299
            datax, datay = adata[i], adata[i + 1]
5✔
300
            if util.true("bins", kwargs):
5✔
301
                rs.append(fit(function, datax, **kwargs))
5✔
302
            else:
303
                rs.append(fit(function, datax, datay, **kwargs))
5✔
304
        return rs
5✔
305

306
    kwargs = plot_kwargs(kwargs)
5✔
307

308
    if np.any(np.iscomplex(datay)):
5✔
309
        label = util.get("label", kwargs, "")
5✔
310
        kwargs["label"] = label + "(real)"
5✔
311
        r = fit(datax, datay.real, function=function, **kwargs)
5✔
312
        kwargs["label"] = label + "(imag)"
5✔
313
        i = fit(datax, datay.imag, function=function, **kwargs)
5✔
314
        return r, i
5✔
315
    if kwargs["auto_fit"]:
5✔
316
        best_f, best_ff, lambda_f = ffit.auto(datax, datay, function, **kwargs)
5✔
317
        if best_f is not None:
5✔
318
            del kwargs["auto_fit"]
5✔
319
            fit(datax, datay, best_f, **kwargs)
5✔
320
        return best_f, best_ff, lambda_f
5✔
321
    if kwargs["also_fit"] == False and kwargs["label"] is None and kwargs["lpos"] == 0:
5✔
322
        kwargs["lpos"] = -1
5✔
323
    return _fit_impl(datax, datay, function, **kwargs)
5✔
324

325

326
def _fit_impl(datax, datay, function, **kwargs):
5✔
327
    x = None
5✔
328
    y = None
5✔
329
    rfit = None
5✔
330
    ifit = None
5✔
331
    fig = None
5✔
332
    fig = init_plot(kwargs)
5✔
333
    ll = None
5✔
334
    if kwargs["also_data"]:
5✔
335
        ll = plt_data(datax, datay, **kwargs).get_color()
5✔
336
    if kwargs["interpolate"]:
5✔
337
        ifit, _, x, y = plt_interpolate(datax, datay, icolor=ll, **kwargs)
5✔
338
    if kwargs["also_fit"]:
5✔
339
        assert function is not None, "function must be given"
5✔
340
        rfit, kwargs["fit_color"], _, _ = plt_fit(datax, datay, function, **kwargs)
5✔
341
    if kwargs["ss"]:
5✔
342
        kwargs["oldshow"] = kwargs["show"]
5✔
343
        kwargs["show"] = kwargs["show"] and not kwargs["residue"]
5✔
344
        save_plot(**kwargs)
5✔
345
        kwargs["show"] = kwargs["oldshow"]
5✔
346
    if kwargs["residue"] and fig is not None:
5✔
347
        plt_residue(datax, datay, function, rfit, fig, **kwargs)
5✔
348
    if not kwargs["also_fit"] and kwargs["interpolate"]:
5✔
349
        return (ifit, x, y)
5✔
350
        # return ifit
351
    return rfit
5✔
352

353

354
# @append_doc(default_kwargs)
355

356

357
def data(*data, function=None, **kwargs):
5✔
358
    """
359
    Plot datay against datax via :func:`fit`
360

361
    Parameters
362
    ----------
363
    datax : array_like
364
        X data either as ``unp.uarray`` or ``np.array`` or ``list``
365
    datay : array_like
366
        Y data either as ``unp.uarray`` or ``np.array`` or ``list``
367
    function : func,optional
368
        Fit function with parameters: ``x``, ``params``
369
    **kwargs : optional
370
        see :func:`plot_kwargs`.
371
    Returns
372
    -------
373
    array_like
374
        Optimized fit parameters of ``function`` to ``datax`` and ``datay``
375
    """
376
    if "also_fit" not in kwargs:
5✔
377
        kwargs["also_fit"] = False
5✔
378
    kwargs = plot_kwargs(kwargs)
5✔
379
    return fit(function=function, *data, **kwargs)
5✔
380

381

382
# @append_doc(default_kwargs)
383

384

385
def auto(*adata, funcs=None, **kwargs):
5✔
386
    """
387
    Automatically loop over functions and fit the best one.
388

389
    Parameters
390
    ----------
391
    funcs : function array
392
        functions to consider as fit. Default all ``smpl.functions``.
393
    **kwargs : optional
394
        see :func:`plot_kwargs`.
395

396
    Returns
397
    -------
398
    The best fit function and it's parameters. Also a lambda function where the parameters are already applied.
399

400

401

402
    """
403
    if "auto_fit" not in kwargs:
5✔
404
        kwargs["auto_fit"] = True
5✔
405
    kwargs = plot_kwargs(kwargs)
5✔
406
    return fit(function=funcs, *adata, **kwargs)
5✔
407

408

409
def _function(
5✔
410
    func,
411
    xfit,
412
    fmt="-",
413
    label=None,
414
    function_color=None,
415
    sigmas=0.0,
416
    alpha=0.4,
417
    **kwargs,
418
):
419
    # kargs = {}
420
    # if util.has("fmt", kwargs):
421
    #    kargs["fmt"] = kwargs["fmt"]
422
    # if util.has("label", kwargs) and kwargs["label"] != "":
423
    #    kargs["label"] = kwargs["label"]
424
    # if util.has("function_color", kwargs) and kwargs["function_color"] != "":
425
    #    kargs["color"] = kwargs["function_color"]
426
    # if util.has("sigmas", kwargs) and kwargs["sigmas"] != "":
427
    #    kargs["sigmas"] = kwargs["sigmas"]
428
    # if util.has("alpha", kwargs) and kwargs["alpha"] != "":
429
    #    kargs["alpha"] = kwargs["alpha"]
430
    # __function(func, xfit,  **kargs)
431

432
    if label == "":
5✔
433
        label = None
5✔
434
    if function_color == "":
5✔
435
        function_color = None
×
436
    if sigmas == "":
5✔
437
        sigmas = 0.0
×
438
    if alpha == "":
5✔
439
        alpha = 0.4
×
440
    __function(
5✔
441
        func,
442
        xfit,
443
        fmt=fmt,
444
        label=label,
445
        color=function_color,
446
        sigmas=sigmas,
447
        alpha=alpha,
448
        **kwargs,
449
    )
450

451

452
def plt_plt(x, y, fmt, color, label, linestyle, **kwargs):
5✔
453
    if linestyle is None and fmt is not None:
5✔
454
        return plt.plot(x, y, fmt, label=label, color=color, **kwargs)
5✔
455
    if linestyle is not None and fmt is None:
5✔
456
        return plt.plot(x, y, label=label, color=color, linestyle=linestyle, **kwargs)
×
457
    if linestyle is None and fmt is None:
5✔
458
        return plt.plot(x, y, label=label, color=color, **kwargs)
5✔
459
    # should not reach here
NEW
460
    raise ValueError(
×
461
        "Either fmt or linestyle must be given, but not both. fmt=%s, linestyle=%s"
462
        % (fmt, linestyle)
463
    )
464

465

466
def __function(
5✔
467
    gfunc,
468
    xlinspace,
469
    fmt="-",
470
    label=None,
471
    color=None,
472
    hatch=None,
473
    sigmas=0.0,
474
    linestyle=None,
475
    alpha=0.4,
476
    **kwargs,
477
):
478
    # filter unused bad kwargs here to avoid passing them down
479
    # TODO it would be better to not pass them down in the first place
480
    for key in [
5✔
481
        "xaxis",
482
        "yaxis",
483
        "xvar",
484
        "xmin",
485
        "xmax",
486
        "xlabel",
487
        "ylabel",
488
        "bins",
489
        "binunc",
490
        "bbox_to_anchor",
491
        "tight",
492
        "residue",
493
        "lpos",
494
        "interpolate",
495
        "params",
496
        "also_fit",
497
        "init",
498
        "frange",
499
        "epsfcn",
500
        "units",
501
        "fselector",
502
        "maxfev",
503
        "sortbyx",
504
        "xerror",
505
        "yerror",
506
        "fixed_params",
507
        "autotqdm",
508
        "fitter",
509
        "title",
510
        "where",
511
        "save",
512
        "prange",
513
        "ss",
514
        "also_data",
515
        "auto_fit",
516
        "data_sigmas",
517
        "logy",
518
        "logx",
519
        "data_color",
520
        "fit_color",
521
        "fit_fmt",
522
        "show",
523
        "size",
524
        "number_format",
525
        "selector",
526
        "fitinline",
527
        "grid",
528
        "hist",
529
        "stairs",
530
        "capsize",
531
        "axes",
532
        "xspace",
533
        "extrapolate",
534
        "extrapolate_min",
535
        "extrapolate_max",
536
        "extrapolate_fmt",
537
        "extrapolate_hatch",
538
        "function_color",
539
        "residue_err",
540
        "interpolate_fmt",
541
        "interpolate_label",
542
        "ncol",
543
        "steps",
544
        "interpolator",
545
        "next_color",
546
    ]:
547
        kwargs.pop(key, None)
5✔
548
    func = gfunc
5✔
549
    x = xlinspace
5✔
550
    l = label
5✔
551

552
    if isinstance(func(x)[0], uncertainties.UFloat):
5✔
553
        if sigmas > 0:
5✔
554
            (ll,) = plt_plt(
5✔
555
                x,
556
                unv(func(x)),
557
                fmt,
558
                label=None,
559
                color=color,
560
                linestyle=linestyle,
561
                **kwargs,
562
            )
563
            y = func(x)
5✔
564
            plt.fill_between(
5✔
565
                x,
566
                unv(y) - sigmas * usd(y),
567
                unv(y) + sigmas * usd(y),
568
                alpha=alpha,
569
                label=l,
570
                color=ll.get_color(),
571
                hatch=hatch,
572
                **kwargs,
573
            )
574
        else:
575
            (ll,) = plt_plt(
5✔
576
                x,
577
                unv(func(x)),
578
                fmt,
579
                label=l,
580
                color=color,
581
                linestyle=linestyle,
582
                **kwargs,
583
            )
584
    else:
585
        (ll,) = plt_plt(
5✔
586
            x, func(x), fmt, label=l, color=color, linestyle=linestyle, **kwargs
587
        )
588
    return ll
5✔
589

590

591
def function(func, *args, fmt="-", **kwargs):
5✔
592
    """
593
    Plot function ``func`` between ``xmin`` and ``xmax``
594

595
    Parameters
596
    ----------
597
    func : function
598
        Function to be plotted between ``xmin`` and ``xmax``, only taking `array_like` ``x`` as parameter
599
    *args : optional
600
        arguments for ``func``
601
    **kwargs : optional
602
        see :func:`plot_kwargs`.
603
    """
604
    kwargs["fmt"] = fmt
5✔
605
    if not util.has("xmin", kwargs) or not util.has("xmax", kwargs):
5✔
606
        kwargs["xmin"], kwargs["xmax"] = stat.get_interesting_domain(func)
5✔
607
        # raise Exception("xmin or xmax missing.")
608

609
    # if not util.has('lpos', kwargs) and not util.has('label', kwargs):
610
    #    kwargs['lpos'] = -1
611

612
    if "label" not in kwargs:
5✔
613
        kwargs = plot_kwargs(kwargs)
5✔
614
        kwargs["label"] = get_fnc_legend(func, args, **kwargs)
5✔
615
    else:
616
        kwargs = plot_kwargs(kwargs)
5✔
617

618
    xlin = kwargs["xspace"](kwargs["xmin"], kwargs["xmax"], kwargs["steps"])
5✔
619
    init_plot(kwargs)
5✔
620

621
    # kwargs['lpos'] = 0
622
    # _plot(xfit, func(xfit, *args), **kwargs)
623
    _function(wrap.get_lambda_argd(func, kwargs["xvar"], *args), xlin, **kwargs)
5✔
624
    if kwargs["ss"]:
5✔
625
        save_plot(**kwargs)
5✔
626

627

628
# xaxis="",yaxis="",fit_color=None,save = None,residue_err=True,show=False):
629
def plt_residue(datax, datay, gfunction, rfit, fig, **kwargs):
5✔
630
    function = wrap.get_lambda(gfunction, kwargs["xvar"])
5✔
631
    fig.add_axes((0.1, 0.1, 0.8, 0.2))
5✔
632
    kwargs["yaxis"] = "$\\Delta$" + kwargs["yaxis"]
5✔
633
    kwargs["data_color"] = kwargs["fit_color"]
5✔
634

635
    if kwargs["residue_err"]:
5✔
636
        plt_data(datax, datay - function(datax, *rfit), **kwargs)
5✔
637
    else:
638
        plt_data(unv(datax), unv(datay - function(datax, *rfit)), **kwargs)
5✔
639
    kwargs["lpos"] = -1
5✔
640
    save_plot(**kwargs)
5✔
641

642

643
def data_split(datax, datay, **kwargs):
5✔
644
    return ffit.data_split(datax, datay, **kwargs)
5✔
645

646

647
def _fit(datax, datay, function, **kwargs):
5✔
648
    """
649
    Returns a fit like :func:`fit` but does no plotting.
650
    """
651
    return ffit.fit(datax, datay, function, **kwargs)
5✔
652

653

654
def plt_data(datax, datay, **kwargs):
5✔
655
    """
656
    Plot datay vs datax
657
    """
658
    x, y, xerr, yerr = data_split(datax, datay, **kwargs)
5✔
659
    if xerr is not None:
5✔
660
        xerr = xerr * kwargs["data_sigmas"]
5✔
661
    if yerr is not None:
5✔
662
        yerr = yerr * kwargs["data_sigmas"]
5✔
663

664
    ll = None
5✔
665
    if xerr is None and yerr is None:
5✔
666
        if kwargs["fmt"] is None:
5✔
667
            if kwargs["linestyle"] is None:
×
668
                (ll,) = plt.plot(
×
669
                    x, y, label=kwargs["label"], color=kwargs["data_color"]
670
                )
671
            else:
672
                (ll,) = plt.plot(
×
673
                    x,
674
                    y,
675
                    label=kwargs["label"],
676
                    color=kwargs["data_color"],
677
                    linestyle=kwargs["linestyle"],
678
                )
679
        elif kwargs["fmt"] == "step":
5✔
680
            (ll,) = plt.step(
×
681
                x,
682
                y,
683
                where=kwargs["where"],
684
                label=kwargs["label"],
685
                color=kwargs["data_color"],
686
            )
687
        elif kwargs["fmt"] == "hist":
5✔
688
            (ll,) = plt.step(
5✔
689
                x,
690
                y,
691
                where=kwargs["where"],
692
                label=kwargs["label"],
693
                color=kwargs["data_color"],
694
            )
695
            plt.fill_between(x, y, step="mid", color=ll.get_color())
5✔
696
        else:
697
            (ll,) = plt.plot(
5✔
698
                x, y, kwargs["fmt"], label=kwargs["label"], color=kwargs["data_color"]
699
            )
700
    elif kwargs["fmt"] is None:
5✔
701
        if kwargs["linestyle"] is None:
5✔
702
            (
5✔
703
                ll,
704
                _,
705
                _,
706
            ) = plt.errorbar(
707
                x,
708
                y,
709
                yerr=yerr,
710
                xerr=xerr,
711
                fmt=" ",
712
                capsize=kwargs["capsize"],
713
                label=kwargs["label"],
714
                color=kwargs["data_color"],
715
            )
716
        else:
717
            (
1✔
718
                ll,
719
                _,
720
                _,
721
            ) = plt.errorbar(
722
                x,
723
                y,
724
                yerr=yerr,
725
                xerr=xerr,
726
                fmt=" ",
727
                capsize=kwargs["capsize"],
728
                label=kwargs["label"],
729
                color=kwargs["data_color"],
730
                linestyle=kwargs["linestyle"],
731
            )
732
    elif kwargs["fmt"] == "step":
5✔
733
        (ll,) = plt.step(x, y, where=kwargs["where"], color=kwargs["data_color"])
5✔
734
        if xerr is not None:
5✔
735
            for ix, xv in enumerate(x):
5✔
736
                dx = xerr[ix]
5✔
737
                tx = [xv - dx, xv + dx]
5✔
738
                plt.fill_between(
5✔
739
                    tx,
740
                    y[ix] - yerr[ix],
741
                    y[ix] + yerr[ix],
742
                    label=kwargs["label"] if ix == 1 else None,
743
                    alpha=kwargs["alpha"],
744
                    step="pre",
745
                    color=ll.get_color(),
746
                )
747
        else:
748
            plt.fill_between(
5✔
749
                x,
750
                y - yerr,
751
                y + yerr,
752
                label=kwargs["label"],
753
                alpha=kwargs["alpha"],
754
                step="mid",
755
                color=ll.get_color(),
756
            )
757
    elif kwargs["fmt"] == "hist":
5✔
758
        (
5✔
759
            ll,
760
            _,
761
            _,
762
        ) = plt.errorbar(
763
            x,
764
            y,
765
            yerr=yerr,
766
            xerr=xerr,
767
            fmt=" ",
768
            capsize=kwargs["capsize"],
769
            color="black",
770
        )
771
        plt.fill_between(x, y, step="mid", label=kwargs["label"], color=ll.get_color())
5✔
772
    else:
773
        (
5✔
774
            ll,
775
            _,
776
            _,
777
        ) = plt.errorbar(
778
            x,
779
            y,
780
            yerr=yerr,
781
            xerr=xerr,
782
            fmt=kwargs["fmt"],
783
            capsize=kwargs["capsize"],
784
            label=kwargs["label"],
785
            color=kwargs["data_color"],
786
        )
787
    return ll
5✔
788

789

790
def get_fnc_legend(function, rfit, **kwargs):
5✔
791
    l = wrap.get_latex(function)
5✔
792

793
    vnames = wrap.get_varnames(function, kwargs["xvar"])
5✔
794
    for i in range(1, len(vnames)):
5✔
795
        l = l + ("\n" if not kwargs["fitinline"] or i == 1 else " ")
5✔
796
        l = l + "$" + sympy.latex(sympy.symbols(str(vnames[i]))) + "$="
5✔
797
        if kwargs["units"] is not None and usd(rfit[i - 1]) > 0:
5✔
798
            l = l + "("
5✔
799
        if "number_format" in kwargs:
5✔
800
            l = l + kwargs["number_format"].format(rfit[i - 1])
5✔
801
        else:
802
            l = l + "%s" % (rfit[i - 1])
×
803

804
        if kwargs["units"] is not None and usd(rfit[i - 1]) > 0:
5✔
805
            l = l + ")"
5✔
806
        if kwargs["units"] is not None:
5✔
807
            l = l + " " + kwargs["units"][i - 1]
5✔
808
    return l
5✔
809

810

811
def plt_fit_or_interpolate(
5✔
812
    datax, datay, fitted, l=None, c=None, f=None, ls=None, **kwargs
813
):
814
    # just filter these kwargs out, so they dont get passed down and are replaced by above args
815
    # TODO why not pass label=XXX directly to this?
816
    #      -> probably since there are cases where both e.g. color and replace color are needed
817
    for key in ["color", "label", "fmt", "linestyle", "hatch"]:
5✔
818
        kwargs.pop(key, None)
5✔
819
    if kwargs["prange"] is None:
5✔
820
        x, _, _, _ = ffit.fit_split(datax, datay, **kwargs)
5✔
821
        xfit = kwargs["xspace"](np.min(unv(x)), np.max(unv(x)), kwargs["steps"])
5✔
822
    else:
823
        xfit = kwargs["xspace"](
×
824
            kwargs["prange"][0], kwargs["prange"][1], kwargs["steps"]
825
        )
826
    ll = __function(
5✔
827
        fitted,
828
        xfit,
829
        kwargs["fit_fmt"] if f is not None and ls is None else f,
830
        label=l,
831
        color=kwargs["fit_color"] if c is None else c,
832
        linestyle=ls,
833
        **kwargs,
834
    )
835

836
    if (
5✔
837
        (
838
            (kwargs["frange"] is not None or kwargs["fselector"] is not None)
839
            and util.true("extrapolate", kwargs)
840
        )
841
        or util.has("extrapolate_max", kwargs)
842
        or util.has("extrapolate_min", kwargs)
843
    ):
844
        xxfit = kwargs["xspace"](
5✔
845
            util.get("extrapolate_min", kwargs, np.min(unv(datax))),
846
            util.get("extrapolate_max", kwargs, np.max(unv(datax))),
847
            kwargs["steps"],
848
        )
849
        for pmin, pmax in [
5✔
850
            (np.min(xxfit), np.min(xfit)),
851
            (np.max(xfit), np.max(xxfit)),
852
        ]:
853
            __function(
5✔
854
                fitted,
855
                kwargs["xspace"](pmin, pmax, kwargs["steps"]),
856
                util.get("extrapolate_fmt", kwargs, "--"),
857
                color=ll.get_color(),
858
                hatch=util.get("extrapolate_hatch", kwargs, r"||"),
859
                **kwargs,
860
            )
861
    return ll.get_color(), xfit, fitted(xfit)
5✔
862

863

864
def plt_interpolate(datax, datay, icolor=None, **kwargs):
5✔
865
    """
866
    Interpolate and Plot that Interpolation.
867
    """
868
    inter = interpolate.interpolate(datax, datay, **kwargs)
5✔
869
    kargs = {}
5✔
870
    if isinstance(kwargs["interpolate_fmt"], tuple):
5✔
871
        kargs["ls"] = kwargs["interpolate_fmt"]
×
872
    else:
873
        kargs["f"] = kwargs["interpolate_fmt"]
5✔
874
    if kwargs["interpolate_label"] is not None:
5✔
875
        kargs["l"] = kwargs["interpolate_label"]
5✔
876
    # l = None so that no label
877
    return (
5✔
878
        inter,
879
        *plt_fit_or_interpolate(datax, datay, inter, c=icolor, **kargs, **kwargs),
880
    )
881

882

883
def plt_fit(datax, datay, gfunction, **kwargs):
5✔
884
    """
885
    Fit and Plot that Fit.
886
    """
887
    func = wrap.get_lambda(gfunction, kwargs["xvar"])
5✔
888
    rfit = _fit(datax, datay, gfunction, **kwargs)
5✔
889

890
    def fitted(x):
5✔
891
        return func(x, *rfit)
5✔
892

893
    vnames = wrap.get_varnames(gfunction, kwargs["xvar"])
5✔
894
    for v in vnames[1:]:  # remove fixed parameters from kwargs
5✔
895
        kwargs.pop(v, None)
5✔
896

897
    l = get_fnc_legend(gfunction, rfit, **kwargs)
5✔
898
    return (rfit, *plt_fit_or_interpolate(datax, datay, fitted, l, **kwargs))
5✔
899

900

901
def init_plot(kwargs):
5✔
902
    fig = None
5✔
903
    if util.has("axes", kwargs) and kwargs["axes"] is not None:
5✔
904
        plt.sca(kwargs["axes"])
5✔
905
        fig = kwargs["axes"].get_figure()
5✔
906
    if kwargs["init"] or util.true("residue", kwargs):
5✔
907
        if kwargs["size"] is None:
5✔
908
            fig = plt.figure()
5✔
909
        else:
910
            fig = plt.figure(figsize=kwargs["size"])
×
911
        if kwargs["residue"]:
5✔
912
            fig.add_axes((0.1, 0.3, 0.8, 0.6))
5✔
913
    if util.has("next_color", kwargs) and not kwargs["next_color"]:
5✔
914
        lines = plt.gca()._get_lines
5✔
915
        tmp_color = lines._cycler_items[lines._idx]["color"]
5✔
916

917
        if kwargs["data_color"] is None:
5✔
918
            kwargs["data_color"] = tmp_color
5✔
919
        if kwargs["fit_color"] is None:
5✔
920
            kwargs["fit_color"] = tmp_color
5✔
921
        if kwargs["function_color"] is None:
5✔
922
            kwargs["function_color"] = tmp_color
5✔
923
    return fig
5✔
924

925

926
def save_plot(**kwargs):
5✔
927
    """
928
    save plot
929
    """
930
    smplr.style_plot1d(**kwargs)
5✔
931
    if "lpos" in kwargs and kwargs["lpos"] >= 0:
5✔
932
        if util.has("bbox_to_anchor", kwargs):
5✔
933
            if util.has("ncol", kwargs):
5✔
934
                plt.legend(
5✔
935
                    loc=kwargs["lpos"],
936
                    bbox_to_anchor=kwargs["bbox_to_anchor"],
937
                    ncol=kwargs["ncol"],
938
                    borderaxespad=0,
939
                )
940
            else:
941
                plt.legend(loc=kwargs["lpos"], bbox_to_anchor=kwargs["bbox_to_anchor"])
5✔
942
        else:
943
            plt.legend(loc=kwargs["lpos"])
5✔
944
    if "save" in kwargs and kwargs["save"] is not None:
5✔
945
        io.mkdirs(kwargs["save"])
×
946
        plt.savefig(kwargs["save"] + ".pdf")
×
947
    if kwargs.get("show"):
5✔
948
        show(**kwargs)
5✔
949

950

951
def show(**kwargs):
5✔
952
    kwargs = plot_kwargs(kwargs)
5✔
953

954
    smplr.style_plot1d(**kwargs)
5✔
955
    plt.show()
5✔
956

957

958
from smpl.plot2d import plot2d as _plot2d
5✔
959
from smpl.plot2d import plot2d_kwargs as _plot2d_kwargs
5✔
960

961

962
def plot2d(*args, **kwargs):
5✔
963
    _plot2d(*args, **kwargs)
5✔
964

965

966
def plot2d_kwargs(*args, **kwargs):
5✔
967
    _plot2d_kwargs(*args, **kwargs)
×
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc