1
"""Plot posterior densities."""
2 6
from ..data import convert_to_dataset
3 6
from ..rcparams import rcParams
4 6
from ..utils import _var_names, credible_interval_warning, get_coords
5 6
from .plot_utils import default_grid, filter_plotters_list, get_plotting_function, xarray_var_iter
6

7

8 6
def plot_posterior(
9
    data,
10
    var_names=None,
11
    filter_vars=None,
12
    transform=None,
13
    coords=None,
14
    figsize=None,
15
    textsize=None,
16
    hdi_prob=None,
17
    multimodal=False,
18
    skipna=False,
19
    round_to=None,
20
    point_estimate="auto",
21
    group="posterior",
22
    rope=None,
23
    ref_val=None,
24
    kind="kde",
25
    bw="default",
26
    circular=False,
27
    bins=None,
28
    ax=None,
29
    backend=None,
30
    backend_kwargs=None,
31
    show=None,
32
    credible_interval=None,
33
    **kwargs
34
):
35
    """Plot Posterior densities in the style of John K. Kruschke's book.
36

37
    Parameters
38
    ----------
39
    data: obj
40
        Any object that can be converted to an az.InferenceData object
41
        Refer to documentation of az.convert_to_dataset for details
42
    var_names: list of variable names
43
        Variables to be plotted, two variables are required. Prefix the variables by `~`
44
        when you want to exclude them from the plot.
45
    filter_vars: {None, "like", "regex"}, optional, default=None
46
        If `None` (default), interpret var_names as the real variables names. If "like",
47
        interpret var_names as substrings of the real variables names. If "regex",
48
        interpret var_names as regular expressions on the real variables names. A la
49
        `pandas.filter`.
50
    transform: callable
51
        Function to transform data (defaults to None i.e.the identity function)
52
    coords: mapping, optional
53
        Coordinates of var_names to be plotted. Passed to `Dataset.sel`
54
    figsize: tuple
55
        Figure size. If None it will be defined automatically.
56
    textsize: float
57
        Text size scaling factor for labels, titles and lines. If None it will be autoscaled based
58
        on figsize.
59
    hdi_prob: float, optional
60
        Plots highest density interval for chosen percentage of density.
61
        Use 'hide' to hide the highest density interval. Defaults to 0.94.
62
    multimodal: bool
63
        If true (default) it may compute more than one credible interval if the distribution is
64
        multimodal and the modes are well separated.
65
    skipna : bool
66
        If true ignores nan values when computing the hdi and point estimates. Defaults to false.
67
    round_to: int, optional
68
        Controls formatting of floats. Defaults to 2 or the integer part, whichever is bigger.
69
    point_estimate: Optional[str]
70
        Plot point estimate per variable. Values should be 'mean', 'median', 'mode' or None.
71
        Defaults to 'auto' i.e. it falls back to default set in rcParams.
72
    group: str, optional
73
        Specifies which InferenceData group should be plotted. Defaults to ‘posterior’.
74
    rope: tuple or dictionary of tuples
75
        Lower and upper values of the Region Of Practical Equivalence. If a list is provided, its
76
        length should match the number of variables.
77
    ref_val: float or dictionary of floats
78
        display the percentage below and above the values in ref_val. Must be None (default),
79
        a constant, a list or a dictionary like see an example below. If a list is provided, its
80
        length should match the number of variables.
81
    kind: str
82
        Type of plot to display (kde or hist) For discrete variables this argument is ignored and
83
        a histogram is always used.
84
    bw: float or str, optional
85
        If numeric, indicates the bandwidth and must be positive.
86
        If str, indicates the method to estimate the bandwidth and must be
87
        one of "scott", "silverman", "isj" or "experimental" when `circular` is False
88
        and "taylor" (for now) when `circular` is True.
89
        Defaults to "default" which means "experimental" when variable is not circular
90
        and "taylor" when it is. Only works if `kind == kde`.
91
    circular: bool, optional
92
        If True, it interprets the values passed are from a circular variable measured in radians
93
        and a circular KDE is used. Only valid for 1D KDE. Defaults to False.
94
        Only works if `kind == kde`.
95
    bins: integer or sequence or 'auto', optional
96
        Controls the number of bins, accepts the same keywords `matplotlib.hist()` does. Only works
97
        if `kind == hist`. If None (default) it will use `auto` for continuous variables and
98
        `range(xmin, xmax + 1)` for discrete variables.
99
    ax: numpy array-like of matplotlib axes or bokeh figures, optional
100
        A 2D array of locations into which to plot the densities. If not supplied, Arviz will create
101
        its own array of plot areas (and return it).
102
    backend: str, optional
103
        Select plotting backend {"matplotlib","bokeh"}. Default "matplotlib".
104
    backend_kwargs: bool, optional
105
        These are kwargs specific to the backend being used. For additional documentation
106
        check the plotting method of the backend.
107
    show: bool, optional
108
        Call backend show function.
109
    credible_interval: float or str, optional
110
        deprecated: Please see hdi_prob
111
    **kwargs
112
        Passed as-is to plt.hist() or plt.plot() function depending on the value of `kind`.
113

114
    Returns
115
    -------
116
    axes: matplotlib axes or bokeh figures
117

118
    Examples
119
    --------
120
    Show a default kernel density plot following style of John Kruschke
121

122
    .. plot::
123
        :context: close-figs
124

125
        >>> import arviz as az
126
        >>> data = az.load_arviz_data('centered_eight')
127
        >>> az.plot_posterior(data)
128

129
    Plot subset variables by specifying variable name exactly
130

131
    .. plot::
132
        :context: close-figs
133

134
        >>> az.plot_posterior(data, var_names=['mu'])
135

136
    Plot Region of Practical Equivalence (rope) and select variables with regular expressions
137

138
    .. plot::
139
        :context: close-figs
140

141
        >>> az.plot_posterior(data, var_names=['mu', '^the'], filter_vars="regex", rope=(-1, 1))
142

143
    Plot Region of Practical Equivalence for selected distributions
144

145
    .. plot::
146
        :context: close-figs
147

148
        >>> rope = {'mu': [{'rope': (-2, 2)}], 'theta': [{'school': 'Choate', 'rope': (2, 4)}]}
149
        >>> az.plot_posterior(data, var_names=['mu', 'theta'], rope=rope)
150

151

152
    Add reference lines
153

154
    .. plot::
155
        :context: close-figs
156

157
        >>> az.plot_posterior(data, var_names=['mu', 'theta'], ref_val=0)
158

159
    Show point estimate of distribution
160

161
    .. plot::
162
        :context: close-figs
163

164
        >>> az.plot_posterior(data, var_names=['mu', 'theta'], point_estimate='mode')
165

166
    Show reference values using variable names and coordinates
167

168
    .. plot::
169
        :context: close-figs
170

171
        >>> az.plot_posterior(data, ref_val= {"theta": [{"school": "Deerfield", "ref_val": 4},
172
        ...                                             {"school": "Choate", "ref_val": 3}]})
173

174
    Show reference values using a list
175

176
    .. plot::
177
        :context: close-figs
178

179
        >>> az.plot_posterior(data, ref_val=[1] + [5] * 8 + [1])
180

181

182
    Plot posterior as a histogram
183

184
    .. plot::
185
        :context: close-figs
186

187
        >>> az.plot_posterior(data, var_names=['mu'], kind='hist')
188

189
    Change size of highest density interval
190

191
    .. plot::
192
        :context: close-figs
193

194
        >>> az.plot_posterior(data, var_names=['mu'], hdi_prob=.75)
195
    """
196 4
    if credible_interval:
197 0
        hdi_prob = credible_interval_warning(credible_interval, hdi_prob)
198

199 4
    data = convert_to_dataset(data, group=group)
200 4
    if transform is not None:
201 0
        data = transform(data)
202 4
    var_names = _var_names(var_names, data, filter_vars)
203

204 4
    if coords is None:
205 4
        coords = {}
206

207 4
    if hdi_prob is None:
208 4
        hdi_prob = rcParams["stats.hdi_prob"]
209 4
    elif hdi_prob not in (None, "hide"):
210 0
        if not 1 >= hdi_prob > 0:
211 0
            raise ValueError("The value of hdi_prob should be in the interval (0, 1]")
212

213 4
    if point_estimate == "auto":
214 4
        point_estimate = rcParams["plot.point_estimate"]
215 4
    elif point_estimate not in {"mean", "median", "mode", None}:
216 4
        raise ValueError("The value of point_estimate must be either mean, median, mode or None.")
217

218 4
    plotters = filter_plotters_list(
219
        list(xarray_var_iter(get_coords(data, coords), var_names=var_names, combined=True)),
220
        "plot_posterior",
221
    )
222 4
    length_plotters = len(plotters)
223 4
    rows, cols = default_grid(length_plotters)
224

225 4
    posteriorplot_kwargs = dict(
226
        ax=ax,
227
        length_plotters=length_plotters,
228
        rows=rows,
229
        cols=cols,
230
        figsize=figsize,
231
        plotters=plotters,
232
        bw=bw,
233
        circular=circular,
234
        bins=bins,
235
        kind=kind,
236
        point_estimate=point_estimate,
237
        round_to=round_to,
238
        hdi_prob=hdi_prob,
239
        multimodal=multimodal,
240
        skipna=skipna,
241
        textsize=textsize,
242
        ref_val=ref_val,
243
        rope=rope,
244
        kwargs=kwargs,
245
        backend_kwargs=backend_kwargs,
246
        show=show,
247
    )
248

249 4
    if backend is None:
250 4
        backend = rcParams["plot.backend"]
251 4
    backend = backend.lower()
252

253
    # TODO: Add backend kwargs
254 4
    plot = get_plotting_function("plot_posterior", "posteriorplot", backend)
255 4
    ax = plot(**posteriorplot_kwargs)
256 4
    return ax

Read our documentation on viewing source code .

Loading