1
# pylint: disable=unexpected-keyword-arg
2 6
"""Plot distribution as histogram or kernel density estimates."""
3 6
import numpy as np
4 6
import xarray as xr
5

6 6
from ..data import InferenceData
7 6
from ..rcparams import rcParams
8 6
from .plot_utils import get_plotting_function
9

10

11 6
def plot_dist(
12
    values,
13
    values2=None,
14
    color="C0",
15
    kind="auto",
16
    cumulative=False,
17
    label=None,
18
    rotated=False,
19
    rug=False,
20
    bw="default",
21
    circular=False,
22
    quantiles=None,
23
    contour=True,
24
    fill_last=True,
25
    figsize=None,
26
    textsize=None,
27
    plot_kwargs=None,
28
    fill_kwargs=None,
29
    rug_kwargs=None,
30
    contour_kwargs=None,
31
    contourf_kwargs=None,
32
    pcolormesh_kwargs=None,
33
    hist_kwargs=None,
34
    is_circular=False,
35
    ax=None,
36
    backend=None,
37
    backend_kwargs=None,
38
    show=None,
39
    **kwargs
40
):
41
    """Plot distribution as histogram or kernel density estimates.
42

43
    By default continuous variables are plotted using KDEs and discrete ones using histograms
44

45
    Parameters
46
    ----------
47
    values : array-like
48
        Values to plot
49
    values2 : array-like, optional
50
        Values to plot. If present, a 2D KDE or a hexbin will be estimated
51
    color : string
52
        valid matplotlib color
53
    kind : string
54
        By default ("auto") continuous variables are plotted using KDEs and discrete ones using
55
        histograms. To override this use "hist" to plot histograms and "kde" for KDEs
56
    cumulative : bool
57
        If true plot the estimated cumulative distribution function. Defaults to False.
58
        Ignored for 2D KDE
59
    label : string
60
        Text to include as part of the legend
61
    rotated : bool
62
        Whether to rotate the 1D KDE plot 90 degrees.
63
    rug : bool
64
        If True adds a rugplot. Defaults to False. Ignored for 2D KDE
65
    bw: Optional[float or str]
66
        If numeric, indicates the bandwidth and must be positive.
67
        If str, indicates the method to estimate the bandwidth and must be
68
        one of "scott", "silverman", "isj" or "experimental" when `circular` is False
69
        and "taylor" (for now) when `circular` is True.
70
        Defaults to "default" which means "experimental" when variable is not circular
71
        and "taylor" when it is.
72
    circular: Optional[bool]
73
        If True, it interprets the values passed are from a circular variable measured in radians
74
        and a circular KDE is used. Only valid for 1D KDE. Defaults to False.
75
    quantiles : list
76
        Quantiles in ascending order used to segment the KDE. Use [.25, .5, .75] for quartiles.
77
        Defaults to None.
78
    contour : bool
79
        If True plot the 2D KDE using contours, otherwise plot a smooth 2D KDE. Defaults to True.
80
    fill_last : bool
81
        If True fill the last contour of the 2D KDE plot. Defaults to True.
82
    figsize : tuple
83
        Figure size. If None it will be defined automatically.
84
    textsize: float
85
        Text size scaling factor for labels, titles and lines. If None it will be autoscaled based
86
        on figsize. Not implemented for bokeh backend.
87
    plot_kwargs : dict
88
        Keywords passed to the pdf line of a 1D KDE.
89
    fill_kwargs : dict
90
        Keywords passed to the fill under the line (use fill_kwargs={'alpha': 0} to disable fill).
91
        Ignored for 2D KDE
92
    rug_kwargs : dict
93
        Keywords passed to the rug plot. Ignored if rug=False or for 2D KDE
94
        Use `space` keyword (float) to control the position of the rugplot. The larger this number
95
        the lower the rugplot.
96
    contour_kwargs : dict
97
        Keywords passed to the contourplot. Ignored for 1D KDE.
98
    contourf_kwargs : dict
99
        Keywords passed to ax.contourf. Ignored for 1D KDE.
100
    pcolormesh_kwargs : dict
101
        Keywords passed to ax.pcolormesh. Ignored for 1D KDE.
102
    hist_kwargs : dict
103
        Keywords passed to the histogram.
104
    is_circular : {False, True, "radians", "degrees"}. Default False.
105
        Select input type {"radians", "degrees"} for circular histogram or KDE plot. If True,
106
        default input type is "radians".
107
    ax: axes, optional
108
        Matplotlib axes or bokeh figures.
109
    backend: str, optional
110
        Select plotting backend {"matplotlib","bokeh"}. Default "matplotlib".
111
    backend_kwargs: bool, optional
112
        These are kwargs specific to the backend being used. For additional documentation
113
        check the plotting method of the backend.
114
    show : bool, optional
115
        Call backend show function.
116

117
    Returns
118
    -------
119
    axes : matplotlib axes or bokeh figures
120

121
    Examples
122
    --------
123
    Plot an integer distribution
124

125
    .. plot::
126
        :context: close-figs
127

128
        >>> import numpy as np
129
        >>> import arviz as az
130
        >>> a = np.random.poisson(4, 1000)
131
        >>> az.plot_dist(a)
132

133
    Plot a continuous distribution
134

135
    .. plot::
136
        :context: close-figs
137

138
        >>> b = np.random.normal(0, 1, 1000)
139
        >>> az.plot_dist(b)
140

141
    Add a rug under the Gaussian distribution
142

143
    .. plot::
144
        :context: close-figs
145

146
        >>> az.plot_dist(b, rug=True)
147

148
    Segment into quantiles
149

150
    .. plot::
151
        :context: close-figs
152

153
        >>> az.plot_dist(b, rug=True, quantiles=[.25, .5, .75])
154

155
    Plot as the cumulative distribution
156

157
    .. plot::
158
        :context: close-figs
159

160
        >>> az.plot_dist(b, rug=True, quantiles=[.25, .5, .75], cumulative=True)
161
    """
162 4
    values = np.asarray(values)
163

164 4
    if isinstance(values, (InferenceData, xr.Dataset)):
165 0
        raise ValueError(
166
            "InferenceData or xarray.Dataset object detected,"
167
            " use plot_posterior, plot_density or plot_pair"
168
            " instead of plot_dist"
169
        )
170

171 4
    if kind not in ["auto", "kde", "hist"]:
172 0
        raise TypeError('Invalid "kind":{}. Select from {{"auto","kde","hist"}}'.format(kind))
173

174 4
    if kind == "auto":
175 4
        kind = "hist" if values.dtype.kind == "i" else "kde"
176

177 4
    dist_plot_args = dict(
178
        # User Facing API that can be simplified
179
        values=values,
180
        values2=values2,
181
        color=color,
182
        kind=kind,
183
        cumulative=cumulative,
184
        label=label,
185
        rotated=rotated,
186
        rug=rug,
187
        bw=bw,
188
        circular=circular,
189
        quantiles=quantiles,
190
        contour=contour,
191
        fill_last=fill_last,
192
        figsize=figsize,
193
        textsize=textsize,
194
        plot_kwargs=plot_kwargs,
195
        fill_kwargs=fill_kwargs,
196
        rug_kwargs=rug_kwargs,
197
        contour_kwargs=contour_kwargs,
198
        contourf_kwargs=contourf_kwargs,
199
        pcolormesh_kwargs=pcolormesh_kwargs,
200
        hist_kwargs=hist_kwargs,
201
        ax=ax,
202
        backend_kwargs=backend_kwargs,
203
        is_circular=is_circular,
204
        show=show,
205
        **kwargs,
206
    )
207

208 4
    if backend is None:
209 4
        backend = rcParams["plot.backend"]
210 4
    backend = backend.lower()
211

212 4
    plot = get_plotting_function("plot_dist", "distplot", backend)
213 4
    ax = plot(**dist_plot_args)
214 4
    return ax

Read our documentation on viewing source code .

Loading