1
"""Matplotlib mcseplot."""
2 2
import matplotlib.pyplot as plt
3 2
import numpy as np
4 2
from scipy.stats import rankdata
5

6 2
from ....stats.stats_utils import quantile as _quantile
7 2
from ...plot_utils import _scale_fig_size, make_label
8 2
from . import backend_kwarg_defaults, backend_show, create_axes_grid, matplotlib_kwarg_dealiaser
9

10

11 2
def plot_mcse(
12
    ax,
13
    plotters,
14
    length_plotters,
15
    rows,
16
    cols,
17
    figsize,
18
    errorbar,
19
    rug,
20
    data,
21
    probs,
22
    kwargs,
23
    extra_methods,
24
    mean_mcse,
25
    sd_mcse,
26
    textsize,
27
    text_kwargs,
28
    rug_kwargs,
29
    extra_kwargs,
30
    idata,
31
    rug_kind,
32
    backend_kwargs,
33
    show,
34
):
35
    """Matplotlib mcseplot."""
36 2
    if backend_kwargs is None:
37 2
        backend_kwargs = {}
38

39 2
    backend_kwargs = {
40
        **backend_kwarg_defaults(),
41
        **backend_kwargs,
42
    }
43

44 2
    (figsize, ax_labelsize, titlesize, xt_labelsize, _linewidth, _markersize) = _scale_fig_size(
45
        figsize, textsize, rows, cols
46
    )
47 2
    backend_kwargs.setdefault("figsize", figsize)
48 2
    backend_kwargs["squeeze"] = True
49

50 2
    kwargs = matplotlib_kwarg_dealiaser(kwargs, "plot")
51 2
    kwargs.setdefault("linestyle", "none")
52 2
    kwargs.setdefault("linewidth", _linewidth)
53 2
    kwargs.setdefault("markersize", _markersize)
54 2
    kwargs.setdefault("marker", "_" if errorbar else "o")
55 2
    kwargs.setdefault("zorder", 3)
56

57 2
    extra_kwargs = matplotlib_kwarg_dealiaser(extra_kwargs, "plot")
58 2
    extra_kwargs.setdefault("linestyle", "-")
59 2
    extra_kwargs.setdefault("linewidth", _linewidth / 2)
60 2
    extra_kwargs.setdefault("color", "k")
61 2
    extra_kwargs.setdefault("alpha", 0.5)
62 2
    text_x = None
63 2
    text_va = None
64 2
    if extra_methods:
65 2
        text_kwargs = matplotlib_kwarg_dealiaser(text_kwargs, "text")
66 2
        text_x = text_kwargs.pop("x", 1)
67 2
        text_kwargs.setdefault("fontsize", xt_labelsize * 0.7)
68 2
        text_kwargs.setdefault("alpha", extra_kwargs["alpha"])
69 2
        text_kwargs.setdefault("color", extra_kwargs["color"])
70 2
        text_kwargs.setdefault("horizontalalignment", "right")
71 2
        text_va = text_kwargs.pop("verticalalignment", None)
72

73 2
    if ax is None:
74 2
        _, ax = create_axes_grid(
75
            length_plotters,
76
            rows,
77
            cols,
78
            backend_kwargs=backend_kwargs,
79
        )
80

81 2
    for (var_name, selection, x), ax_ in zip(plotters, np.ravel(ax)):
82 2
        if errorbar or rug:
83 2
            values = data[var_name].sel(**selection).values.flatten()
84 2
        if errorbar:
85 2
            quantile_values = _quantile(values, probs)
86 2
            ax_.errorbar(probs, quantile_values, yerr=x, **kwargs)
87
        else:
88 2
            ax_.plot(probs, x, label="quantile", **kwargs)
89 2
            if extra_methods:
90 2
                mean_mcse_i = mean_mcse[var_name].sel(**selection).values.item()
91 2
                sd_mcse_i = sd_mcse[var_name].sel(**selection).values.item()
92 2
                ax_.axhline(mean_mcse_i, **extra_kwargs)
93 2
                ax_.annotate(
94
                    "mean",
95
                    (text_x, mean_mcse_i),
96
                    va=text_va
97
                    if text_va is not None
98
                    else "bottom"
99
                    if mean_mcse_i > sd_mcse_i
100
                    else "top",
101
                    **text_kwargs,
102
                )
103 2
                ax_.axhline(sd_mcse_i, **extra_kwargs)
104 2
                ax_.annotate(
105
                    "sd",
106
                    (text_x, sd_mcse_i),
107
                    va=text_va
108
                    if text_va is not None
109
                    else "bottom"
110
                    if sd_mcse_i >= mean_mcse_i
111
                    else "top",
112
                    **text_kwargs,
113
                )
114 2
        if rug:
115 2
            rug_kwargs = matplotlib_kwarg_dealiaser(rug_kwargs, "plot")
116 2
            if not hasattr(idata, "sample_stats"):
117 2
                raise ValueError("InferenceData object must contain sample_stats for rug plot")
118 2
            if not hasattr(idata.sample_stats, rug_kind):
119 2
                raise ValueError("InferenceData does not contain {} data".format(rug_kind))
120 2
            rug_kwargs.setdefault("marker", "|")
121 2
            rug_kwargs.setdefault("linestyle", rug_kwargs.pop("ls", "None"))
122 2
            rug_kwargs.setdefault("color", rug_kwargs.pop("c", kwargs.get("color", "C0")))
123 2
            rug_kwargs.setdefault("space", 0.1)
124 2
            rug_kwargs.setdefault("markersize", rug_kwargs.pop("ms", 2 * _markersize))
125

126 2
            mask = idata.sample_stats[rug_kind].values.flatten()
127 2
            values = rankdata(values)[mask]
128 2
            y_min, y_max = ax_.get_ylim()
129 2
            y_min = y_min if errorbar else 0
130 2
            rug_space = (y_max - y_min) * rug_kwargs.pop("space")
131 2
            rug_x, rug_y = values / (len(mask) - 1), np.full_like(values, y_min) - rug_space
132 2
            ax_.plot(rug_x, rug_y, **rug_kwargs)
133 2
            ax_.axhline(y_min, color="k", linewidth=_linewidth, alpha=0.7)
134

135 2
        ax_.set_title(make_label(var_name, selection), fontsize=titlesize, wrap=True)
136 2
        ax_.tick_params(labelsize=xt_labelsize)
137 2
        ax_.set_xlabel("Quantile", fontsize=ax_labelsize, wrap=True)
138 2
        ax_.set_ylabel(
139
            r"Value $\pm$ MCSE for quantiles" if errorbar else "MCSE for quantiles",
140
            fontsize=ax_labelsize,
141
            wrap=True,
142
        )
143 2
        ax_.set_xlim(0, 1)
144 2
        if rug:
145 2
            ax_.yaxis.get_major_locator().set_params(nbins="auto", steps=[1, 2, 5, 10])
146 2
            y_min, y_max = ax_.get_ylim()
147 2
            yticks = ax_.get_yticks()
148 2
            yticks = yticks[(yticks >= y_min) & (yticks < y_max)]
149 2
            ax_.set_yticks(yticks)
150 2
            ax_.set_yticklabels(["{:.3g}".format(ytick) for ytick in yticks])
151 2
        elif not errorbar:
152 2
            ax_.set_ylim(bottom=0)
153

154 2
    if backend_show(show):
155 0
        plt.show()
156

157 2
    return ax

Read our documentation on viewing source code .

Loading