We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
densityplot warning tight_layout
plot density returns the following warning:

_UserWarning: This figure was using constrained_layout==True, but that is incompatible with subplots_adjust and or tight_layout: setting constrained_layout==False. 
  warnings.warn("This figure was using constrained_layout==True, ")_

The solution is to do not use tight_layout()




--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `arviz/plots/densityplot.py`
Content:
```
1 """KDE and histogram plots for multiple variables."""
2 import numpy as np
3 
4 from ..data import convert_to_dataset
5 from ..stats import hpd
6 from .kdeplot import _fast_kde
7 from .plot_utils import (
8     _scale_fig_size,
9     make_label,
10     xarray_var_iter,
11     default_grid,
12     _create_axes_grid,
13 )
14 from ..utils import _var_names
15 
16 
17 # pylint:disable-msg=too-many-function-args
18 def plot_density(
19     data,
20     group="posterior",
21     data_labels=None,
22     var_names=None,
23     credible_interval=0.94,
24     point_estimate="mean",
25     colors="cycle",
26     outline=True,
27     hpd_markers="",
28     shade=0.0,
29     bw=4.5,
30     figsize=None,
31     textsize=None,
32 ):
33     """Generate KDE plots for continuous variables and histograms for discrete ones.
34 
35     Plots are truncated at their 100*(1-alpha)% credible intervals. Plots are grouped per variable
36     and colors assigned to models.
37 
38     Parameters
39     ----------
40     data : Union[Object, Iterator[Object]]
41         Any object that can be converted to an az.InferenceData object, or an Iterator returning
42         a sequence of such objects.
43         Refer to documentation of az.convert_to_dataset for details about such objects.
44     group: Optional[str]
45         Specifies which InferenceData group should be plotted.  Defaults to 'posterior'.
46         Alternative values include 'prior' and any other strings used as dataset keys in the
47         InferenceData.
48     data_labels : Optional[List[str]]
49         List with names for the datasets passed as "data." Useful when plotting more than one
50         dataset.  Must be the same shape as the data parameter.  Defaults to None.
51     var_names: Optional[List[str]]
52         List of variables to plot.  If multiple datasets are supplied and var_names is not None,
53         will print the same set of variables for each dataset.  Defaults to None, which results in
54         all the variables being plotted.
55     credible_interval : float
56         Credible intervals. Should be in the interval (0, 1]. Defaults to 0.94.
57     point_estimate : Optional[str]
58         Plot point estimate per variable. Values should be 'mean', 'median' or None.
59         Defaults to 'mean'.
60     colors : Optional[Union[List[str],str]]
61         List with valid matplotlib colors, one color per model. Alternative a string can be passed.
62         If the string is `cycle`, it will automatically choose a color per model from matplolib's
63         cycle. If a single color is passed, e.g. 'k', 'C2' or 'red' this color will be used for all
64         models. Defaults to `cycle`.
65     outline : bool
66         Use a line to draw KDEs and histograms. Default to True
67     hpd_markers : str
68         A valid `matplotlib.markers` like 'v', used to indicate the limits of the hpd interval.
69         Defaults to empty string (no marker).
70     shade : Optional[float]
71         Alpha blending value for the shaded area under the curve, between 0 (no shade) and 1
72         (opaque). Defaults to 0.
73     bw : Optional[float]
74         Bandwidth scaling factor for the KDE. Should be larger than 0. The higher this number the
75         smoother the KDE will be. Defaults to 4.5 which is essentially the same as the Scott's rule
76         of thumb (the default rule used by SciPy).
77     figsize : Optional[Tuple[int, int]]
78         Figure size. If None it will be defined automatically.
79     textsize: Optional[float]
80         Text size scaling factor for labels, titles and lines. If None it will be autoscaled based
81         on figsize.
82 
83     Returns
84     -------
85     ax : Matplotlib axes
86 
87 
88     Examples
89     --------
90     Plot default density plot
91 
92     .. plot::
93         :context: close-figs
94 
95         >>> import arviz as az
96         >>> centered = az.load_arviz_data('centered_eight')
97         >>> non_centered = az.load_arviz_data('non_centered_eight')
98         >>> az.plot_density([centered, non_centered])
99 
100     Plot subset variables by specifying variable name exactly
101 
102     .. plot::
103         :context: close-figs
104 
105         >>> az.plot_density([centered, non_centered], var_names=["mu"])
106 
107     Plot a specific `az.InferenceData` group
108 
109     .. plot::
110         :context: close-figs
111 
112         >>> az.plot_density([centered, non_centered], var_names=["mu"], group="prior")
113 
114     Specify credible interval
115 
116     .. plot::
117         :context: close-figs
118 
119         >>> az.plot_density([centered, non_centered], var_names=["mu"], credible_interval=.5)
120 
121     Shade plots and/or remove outlines
122 
123     .. plot::
124         :context: close-figs
125 
126         >>> az.plot_density([centered, non_centered], var_names=["mu"], outline=False, shade=.8)
127 
128     Specify binwidth for kernel density estimation
129 
130     .. plot::
131         :context: close-figs
132 
133         >>> az.plot_density([centered, non_centered], var_names=["mu"], bw=.9)
134     """
135     if not isinstance(data, (list, tuple)):
136         datasets = [convert_to_dataset(data, group=group)]
137     else:
138         datasets = [convert_to_dataset(datum, group=group) for datum in data]
139 
140     var_names = _var_names(var_names, datasets)
141 
142     if point_estimate not in ("mean", "median", None):
143         raise ValueError(
144             "Point estimate should be 'mean'," "median' or None, not {}".format(point_estimate)
145         )
146 
147     n_data = len(datasets)
148 
149     if data_labels is None:
150         if n_data > 1:
151             data_labels = ["{}".format(idx) for idx in range(n_data)]
152         else:
153             data_labels = [""]
154     elif len(data_labels) != n_data:
155         raise ValueError(
156             "The number of names for the models ({}) "
157             "does not match the number of models ({})".format(len(data_labels), n_data)
158         )
159 
160     if colors == "cycle":
161         colors = ["C{}".format(idx % 10) for idx in range(n_data)]
162     elif isinstance(colors, str):
163         colors = [colors for _ in range(n_data)]
164 
165     if not 1 >= credible_interval > 0:
166         raise ValueError("The value of credible_interval should be in the interval (0, 1]")
167 
168     to_plot = [list(xarray_var_iter(data, var_names, combined=True)) for data in datasets]
169     all_labels = []
170     length_plotters = []
171     for plotters in to_plot:
172         length_plotters.append(len(plotters))
173         for var_name, selection, _ in plotters:
174             label = make_label(var_name, selection)
175             if label not in all_labels:
176                 all_labels.append(label)
177     length_plotters = max(length_plotters)
178     rows, cols = default_grid(length_plotters, max_cols=3)
179 
180     (figsize, _, titlesize, xt_labelsize, linewidth, markersize) = _scale_fig_size(
181         figsize, textsize, rows, cols
182     )
183 
184     fig, ax = _create_axes_grid(length_plotters, rows, cols, figsize=figsize, squeeze=False)
185 
186     axis_map = {label: ax_ for label, ax_ in zip(all_labels, ax.flatten())}
187     for m_idx, plotters in enumerate(to_plot):
188         for var_name, selection, values in plotters:
189             label = make_label(var_name, selection)
190             _d_helper(
191                 values.flatten(),
192                 label,
193                 colors[m_idx],
194                 bw,
195                 titlesize,
196                 xt_labelsize,
197                 linewidth,
198                 markersize,
199                 credible_interval,
200                 point_estimate,
201                 hpd_markers,
202                 outline,
203                 shade,
204                 axis_map[label],
205             )
206 
207     if n_data > 1:
208         for m_idx, label in enumerate(data_labels):
209             ax[0].plot([], label=label, c=colors[m_idx], markersize=markersize)
210         ax[0].legend(fontsize=xt_labelsize)
211 
212     fig.tight_layout()
213 
214     return ax
215 
216 
217 def _d_helper(
218     vec,
219     vname,
220     color,
221     bw,
222     titlesize,
223     xt_labelsize,
224     linewidth,
225     markersize,
226     credible_interval,
227     point_estimate,
228     hpd_markers,
229     outline,
230     shade,
231     ax,
232 ):
233     """Plot an individual dimension.
234 
235     Parameters
236     ----------
237     vec : array
238         1D array from trace
239     vname : str
240         variable name
241     color : str
242         matplotlib color
243     bw : float
244         Bandwidth scaling factor. Should be larger than 0. The higher this number the smoother the
245         KDE will be. Defaults to 4.5 which is essentially the same as the Scott's rule of thumb
246         (the default used rule by SciPy).
247     titlesize : float
248         font size for title
249     xt_labelsize : float
250        fontsize for xticks
251     linewidth : float
252         Thickness of lines
253     markersize : float
254         Size of markers
255     credible_interval : float
256         Credible intervals. Defaults to 0.94
257     point_estimate : str or None
258         'mean' or 'median'
259     shade : float
260         Alpha blending value for the shaded area under the curve, between 0 (no shade) and 1
261         (opaque). Defaults to 0.
262     ax : matplotlib axes
263     """
264     if vec.dtype.kind == "f":
265         if credible_interval != 1:
266             hpd_ = hpd(vec, credible_interval)
267             new_vec = vec[(vec >= hpd_[0]) & (vec <= hpd_[1])]
268         else:
269             new_vec = vec
270 
271         density, xmin, xmax = _fast_kde(new_vec, bw=bw)
272         density *= credible_interval
273         x = np.linspace(xmin, xmax, len(density))
274         ymin = density[0]
275         ymax = density[-1]
276 
277         if outline:
278             ax.plot(x, density, color=color, lw=linewidth)
279             ax.plot([xmin, xmin], [-ymin / 100, ymin], color=color, ls="-", lw=linewidth)
280             ax.plot([xmax, xmax], [-ymax / 100, ymax], color=color, ls="-", lw=linewidth)
281 
282         if shade:
283             ax.fill_between(x, density, color=color, alpha=shade)
284 
285     else:
286         xmin, xmax = hpd(vec, credible_interval)
287         bins = range(xmin, xmax + 2)
288         if outline:
289             ax.hist(vec, bins=bins, color=color, histtype="step", align="left")
290         if shade:
291             ax.hist(vec, bins=bins, color=color, alpha=shade)
292 
293     if hpd_markers:
294         ax.plot(xmin, 0, hpd_markers, color=color, markeredgecolor="k", markersize=markersize)
295         ax.plot(xmax, 0, hpd_markers, color=color, markeredgecolor="k", markersize=markersize)
296 
297     if point_estimate is not None:
298         if point_estimate == "mean":
299             est = np.mean(vec)
300         elif point_estimate == "median":
301             est = np.median(vec)
302         ax.plot(est, 0, "o", color=color, markeredgecolor="k", markersize=markersize)
303 
304     ax.set_yticks([])
305     ax.set_title(vname, fontsize=titlesize, wrap=True)
306     for pos in ["left", "right", "top"]:
307         ax.spines[pos].set_visible(False)
308     ax.tick_params(labelsize=xt_labelsize)
309
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/arviz/plots/densityplot.py b/arviz/plots/densityplot.py
--- a/arviz/plots/densityplot.py
+++ b/arviz/plots/densityplot.py
@@ -181,7 +181,7 @@
         figsize, textsize, rows, cols
     )
 
-    fig, ax = _create_axes_grid(length_plotters, rows, cols, figsize=figsize, squeeze=False)
+    _, ax = _create_axes_grid(length_plotters, rows, cols, figsize=figsize, squeeze=False)
 
     axis_map = {label: ax_ for label, ax_ in zip(all_labels, ax.flatten())}
     for m_idx, plotters in enumerate(to_plot):
@@ -209,8 +209,6 @@
             ax[0].plot([], label=label, c=colors[m_idx], markersize=markersize)
         ax[0].legend(fontsize=xt_labelsize)
 
-    fig.tight_layout()
-
     return ax

{"golden_diff": "diff --git a/arviz/plots/densityplot.py b/arviz/plots/densityplot.py\n--- a/arviz/plots/densityplot.py\n+++ b/arviz/plots/densityplot.py\n@@ -181,7 +181,7 @@\n         figsize, textsize, rows, cols\n     )\n \n-    fig, ax = _create_axes_grid(length_plotters, rows, cols, figsize=figsize, squeeze=False)\n+    _, ax = _create_axes_grid(length_plotters, rows, cols, figsize=figsize, squeeze=False)\n \n     axis_map = {label: ax_ for label, ax_ in zip(all_labels, ax.flatten())}\n     for m_idx, plotters in enumerate(to_plot):\n@@ -209,8 +209,6 @@\n             ax[0].plot([], label=label, c=colors[m_idx], markersize=markersize)\n         ax[0].legend(fontsize=xt_labelsize)\n \n-    fig.tight_layout()\n-\n     return ax\n", "issue": "densityplot warning tight_layout\nplot density returns the following warning:\r\n\r\n_UserWarning: This figure was using constrained_layout==True, but that is incompatible with subplots_adjust and or tight_layout: setting constrained_layout==False. \r\n  warnings.warn(\"This figure was using constrained_layout==True, \")_\r\n\r\nThe solution is to do not use tight_layout()\r\n\r\n\r\n\n", "before_files": [{"content": "\"\"\"KDE and histogram plots for multiple variables.\"\"\"\nimport numpy as np\n\nfrom ..data import convert_to_dataset\nfrom ..stats import hpd\nfrom .kdeplot import _fast_kde\nfrom .plot_utils import (\n    _scale_fig_size,\n    make_label,\n    xarray_var_iter,\n    default_grid,\n    _create_axes_grid,\n)\nfrom ..utils import _var_names\n\n\n# pylint:disable-msg=too-many-function-args\ndef plot_density(\n    data,\n    group=\"posterior\",\n    data_labels=None,\n    var_names=None,\n    credible_interval=0.94,\n    point_estimate=\"mean\",\n    colors=\"cycle\",\n    outline=True,\n    hpd_markers=\"\",\n    shade=0.0,\n    bw=4.5,\n    figsize=None,\n    textsize=None,\n):\n    \"\"\"Generate KDE plots for continuous variables and histograms for discrete ones.\n\n    Plots are truncated at their 100*(1-alpha)% credible intervals. Plots are grouped per variable\n    and colors assigned to models.\n\n    Parameters\n    ----------\n    data : Union[Object, Iterator[Object]]\n        Any object that can be converted to an az.InferenceData object, or an Iterator returning\n        a sequence of such objects.\n        Refer to documentation of az.convert_to_dataset for details about such objects.\n    group: Optional[str]\n        Specifies which InferenceData group should be plotted.  Defaults to 'posterior'.\n        Alternative values include 'prior' and any other strings used as dataset keys in the\n        InferenceData.\n    data_labels : Optional[List[str]]\n        List with names for the datasets passed as \"data.\" Useful when plotting more than one\n        dataset.  Must be the same shape as the data parameter.  Defaults to None.\n    var_names: Optional[List[str]]\n        List of variables to plot.  If multiple datasets are supplied and var_names is not None,\n        will print the same set of variables for each dataset.  Defaults to None, which results in\n        all the variables being plotted.\n    credible_interval : float\n        Credible intervals. Should be in the interval (0, 1]. Defaults to 0.94.\n    point_estimate : Optional[str]\n        Plot point estimate per variable. Values should be 'mean', 'median' or None.\n        Defaults to 'mean'.\n    colors : Optional[Union[List[str],str]]\n        List with valid matplotlib colors, one color per model. Alternative a string can be passed.\n        If the string is `cycle`, it will automatically choose a color per model from matplolib's\n        cycle. If a single color is passed, e.g. 'k', 'C2' or 'red' this color will be used for all\n        models. Defaults to `cycle`.\n    outline : bool\n        Use a line to draw KDEs and histograms. Default to True\n    hpd_markers : str\n        A valid `matplotlib.markers` like 'v', used to indicate the limits of the hpd interval.\n        Defaults to empty string (no marker).\n    shade : Optional[float]\n        Alpha blending value for the shaded area under the curve, between 0 (no shade) and 1\n        (opaque). Defaults to 0.\n    bw : Optional[float]\n        Bandwidth scaling factor for the KDE. Should be larger than 0. The higher this number the\n        smoother the KDE will be. Defaults to 4.5 which is essentially the same as the Scott's rule\n        of thumb (the default rule used by SciPy).\n    figsize : Optional[Tuple[int, int]]\n        Figure size. If None it will be defined automatically.\n    textsize: Optional[float]\n        Text size scaling factor for labels, titles and lines. If None it will be autoscaled based\n        on figsize.\n\n    Returns\n    -------\n    ax : Matplotlib axes\n\n\n    Examples\n    --------\n    Plot default density plot\n\n    .. plot::\n        :context: close-figs\n\n        >>> import arviz as az\n        >>> centered = az.load_arviz_data('centered_eight')\n        >>> non_centered = az.load_arviz_data('non_centered_eight')\n        >>> az.plot_density([centered, non_centered])\n\n    Plot subset variables by specifying variable name exactly\n\n    .. plot::\n        :context: close-figs\n\n        >>> az.plot_density([centered, non_centered], var_names=[\"mu\"])\n\n    Plot a specific `az.InferenceData` group\n\n    .. plot::\n        :context: close-figs\n\n        >>> az.plot_density([centered, non_centered], var_names=[\"mu\"], group=\"prior\")\n\n    Specify credible interval\n\n    .. plot::\n        :context: close-figs\n\n        >>> az.plot_density([centered, non_centered], var_names=[\"mu\"], credible_interval=.5)\n\n    Shade plots and/or remove outlines\n\n    .. plot::\n        :context: close-figs\n\n        >>> az.plot_density([centered, non_centered], var_names=[\"mu\"], outline=False, shade=.8)\n\n    Specify binwidth for kernel density estimation\n\n    .. plot::\n        :context: close-figs\n\n        >>> az.plot_density([centered, non_centered], var_names=[\"mu\"], bw=.9)\n    \"\"\"\n    if not isinstance(data, (list, tuple)):\n        datasets = [convert_to_dataset(data, group=group)]\n    else:\n        datasets = [convert_to_dataset(datum, group=group) for datum in data]\n\n    var_names = _var_names(var_names, datasets)\n\n    if point_estimate not in (\"mean\", \"median\", None):\n        raise ValueError(\n            \"Point estimate should be 'mean',\" \"median' or None, not {}\".format(point_estimate)\n        )\n\n    n_data = len(datasets)\n\n    if data_labels is None:\n        if n_data > 1:\n            data_labels = [\"{}\".format(idx) for idx in range(n_data)]\n        else:\n            data_labels = [\"\"]\n    elif len(data_labels) != n_data:\n        raise ValueError(\n            \"The number of names for the models ({}) \"\n            \"does not match the number of models ({})\".format(len(data_labels), n_data)\n        )\n\n    if colors == \"cycle\":\n        colors = [\"C{}\".format(idx % 10) for idx in range(n_data)]\n    elif isinstance(colors, str):\n        colors = [colors for _ in range(n_data)]\n\n    if not 1 >= credible_interval > 0:\n        raise ValueError(\"The value of credible_interval should be in the interval (0, 1]\")\n\n    to_plot = [list(xarray_var_iter(data, var_names, combined=True)) for data in datasets]\n    all_labels = []\n    length_plotters = []\n    for plotters in to_plot:\n        length_plotters.append(len(plotters))\n        for var_name, selection, _ in plotters:\n            label = make_label(var_name, selection)\n            if label not in all_labels:\n                all_labels.append(label)\n    length_plotters = max(length_plotters)\n    rows, cols = default_grid(length_plotters, max_cols=3)\n\n    (figsize, _, titlesize, xt_labelsize, linewidth, markersize) = _scale_fig_size(\n        figsize, textsize, rows, cols\n    )\n\n    fig, ax = _create_axes_grid(length_plotters, rows, cols, figsize=figsize, squeeze=False)\n\n    axis_map = {label: ax_ for label, ax_ in zip(all_labels, ax.flatten())}\n    for m_idx, plotters in enumerate(to_plot):\n        for var_name, selection, values in plotters:\n            label = make_label(var_name, selection)\n            _d_helper(\n                values.flatten(),\n                label,\n                colors[m_idx],\n                bw,\n                titlesize,\n                xt_labelsize,\n                linewidth,\n                markersize,\n                credible_interval,\n                point_estimate,\n                hpd_markers,\n                outline,\n                shade,\n                axis_map[label],\n            )\n\n    if n_data > 1:\n        for m_idx, label in enumerate(data_labels):\n            ax[0].plot([], label=label, c=colors[m_idx], markersize=markersize)\n        ax[0].legend(fontsize=xt_labelsize)\n\n    fig.tight_layout()\n\n    return ax\n\n\ndef _d_helper(\n    vec,\n    vname,\n    color,\n    bw,\n    titlesize,\n    xt_labelsize,\n    linewidth,\n    markersize,\n    credible_interval,\n    point_estimate,\n    hpd_markers,\n    outline,\n    shade,\n    ax,\n):\n    \"\"\"Plot an individual dimension.\n\n    Parameters\n    ----------\n    vec : array\n        1D array from trace\n    vname : str\n        variable name\n    color : str\n        matplotlib color\n    bw : float\n        Bandwidth scaling factor. Should be larger than 0. The higher this number the smoother the\n        KDE will be. Defaults to 4.5 which is essentially the same as the Scott's rule of thumb\n        (the default used rule by SciPy).\n    titlesize : float\n        font size for title\n    xt_labelsize : float\n       fontsize for xticks\n    linewidth : float\n        Thickness of lines\n    markersize : float\n        Size of markers\n    credible_interval : float\n        Credible intervals. Defaults to 0.94\n    point_estimate : str or None\n        'mean' or 'median'\n    shade : float\n        Alpha blending value for the shaded area under the curve, between 0 (no shade) and 1\n        (opaque). Defaults to 0.\n    ax : matplotlib axes\n    \"\"\"\n    if vec.dtype.kind == \"f\":\n        if credible_interval != 1:\n            hpd_ = hpd(vec, credible_interval)\n            new_vec = vec[(vec >= hpd_[0]) & (vec <= hpd_[1])]\n        else:\n            new_vec = vec\n\n        density, xmin, xmax = _fast_kde(new_vec, bw=bw)\n        density *= credible_interval\n        x = np.linspace(xmin, xmax, len(density))\n        ymin = density[0]\n        ymax = density[-1]\n\n        if outline:\n            ax.plot(x, density, color=color, lw=linewidth)\n            ax.plot([xmin, xmin], [-ymin / 100, ymin], color=color, ls=\"-\", lw=linewidth)\n            ax.plot([xmax, xmax], [-ymax / 100, ymax], color=color, ls=\"-\", lw=linewidth)\n\n        if shade:\n            ax.fill_between(x, density, color=color, alpha=shade)\n\n    else:\n        xmin, xmax = hpd(vec, credible_interval)\n        bins = range(xmin, xmax + 2)\n        if outline:\n            ax.hist(vec, bins=bins, color=color, histtype=\"step\", align=\"left\")\n        if shade:\n            ax.hist(vec, bins=bins, color=color, alpha=shade)\n\n    if hpd_markers:\n        ax.plot(xmin, 0, hpd_markers, color=color, markeredgecolor=\"k\", markersize=markersize)\n        ax.plot(xmax, 0, hpd_markers, color=color, markeredgecolor=\"k\", markersize=markersize)\n\n    if point_estimate is not None:\n        if point_estimate == \"mean\":\n            est = np.mean(vec)\n        elif point_estimate == \"median\":\n            est = np.median(vec)\n        ax.plot(est, 0, \"o\", color=color, markeredgecolor=\"k\", markersize=markersize)\n\n    ax.set_yticks([])\n    ax.set_title(vname, fontsize=titlesize, wrap=True)\n    for pos in [\"left\", \"right\", \"top\"]:\n        ax.spines[pos].set_visible(False)\n    ax.tick_params(labelsize=xt_labelsize)\n", "path": "arviz/plots/densityplot.py"}], "after_files": [{"content": "\"\"\"KDE and histogram plots for multiple variables.\"\"\"\nimport numpy as np\n\nfrom ..data import convert_to_dataset\nfrom ..stats import hpd\nfrom .kdeplot import _fast_kde\nfrom .plot_utils import (\n    _scale_fig_size,\n    make_label,\n    xarray_var_iter,\n    default_grid,\n    _create_axes_grid,\n)\nfrom ..utils import _var_names\n\n\n# pylint:disable-msg=too-many-function-args\ndef plot_density(\n    data,\n    group=\"posterior\",\n    data_labels=None,\n    var_names=None,\n    credible_interval=0.94,\n    point_estimate=\"mean\",\n    colors=\"cycle\",\n    outline=True,\n    hpd_markers=\"\",\n    shade=0.0,\n    bw=4.5,\n    figsize=None,\n    textsize=None,\n):\n    \"\"\"Generate KDE plots for continuous variables and histograms for discrete ones.\n\n    Plots are truncated at their 100*(1-alpha)% credible intervals. Plots are grouped per variable\n    and colors assigned to models.\n\n    Parameters\n    ----------\n    data : Union[Object, Iterator[Object]]\n        Any object that can be converted to an az.InferenceData object, or an Iterator returning\n        a sequence of such objects.\n        Refer to documentation of az.convert_to_dataset for details about such objects.\n    group: Optional[str]\n        Specifies which InferenceData group should be plotted.  Defaults to 'posterior'.\n        Alternative values include 'prior' and any other strings used as dataset keys in the\n        InferenceData.\n    data_labels : Optional[List[str]]\n        List with names for the datasets passed as \"data.\" Useful when plotting more than one\n        dataset.  Must be the same shape as the data parameter.  Defaults to None.\n    var_names: Optional[List[str]]\n        List of variables to plot.  If multiple datasets are supplied and var_names is not None,\n        will print the same set of variables for each dataset.  Defaults to None, which results in\n        all the variables being plotted.\n    credible_interval : float\n        Credible intervals. Should be in the interval (0, 1]. Defaults to 0.94.\n    point_estimate : Optional[str]\n        Plot point estimate per variable. Values should be 'mean', 'median' or None.\n        Defaults to 'mean'.\n    colors : Optional[Union[List[str],str]]\n        List with valid matplotlib colors, one color per model. Alternative a string can be passed.\n        If the string is `cycle`, it will automatically choose a color per model from matplolib's\n        cycle. If a single color is passed, e.g. 'k', 'C2' or 'red' this color will be used for all\n        models. Defaults to `cycle`.\n    outline : bool\n        Use a line to draw KDEs and histograms. Default to True\n    hpd_markers : str\n        A valid `matplotlib.markers` like 'v', used to indicate the limits of the hpd interval.\n        Defaults to empty string (no marker).\n    shade : Optional[float]\n        Alpha blending value for the shaded area under the curve, between 0 (no shade) and 1\n        (opaque). Defaults to 0.\n    bw : Optional[float]\n        Bandwidth scaling factor for the KDE. Should be larger than 0. The higher this number the\n        smoother the KDE will be. Defaults to 4.5 which is essentially the same as the Scott's rule\n        of thumb (the default rule used by SciPy).\n    figsize : Optional[Tuple[int, int]]\n        Figure size. If None it will be defined automatically.\n    textsize: Optional[float]\n        Text size scaling factor for labels, titles and lines. If None it will be autoscaled based\n        on figsize.\n\n    Returns\n    -------\n    ax : Matplotlib axes\n\n\n    Examples\n    --------\n    Plot default density plot\n\n    .. plot::\n        :context: close-figs\n\n        >>> import arviz as az\n        >>> centered = az.load_arviz_data('centered_eight')\n        >>> non_centered = az.load_arviz_data('non_centered_eight')\n        >>> az.plot_density([centered, non_centered])\n\n    Plot subset variables by specifying variable name exactly\n\n    .. plot::\n        :context: close-figs\n\n        >>> az.plot_density([centered, non_centered], var_names=[\"mu\"])\n\n    Plot a specific `az.InferenceData` group\n\n    .. plot::\n        :context: close-figs\n\n        >>> az.plot_density([centered, non_centered], var_names=[\"mu\"], group=\"prior\")\n\n    Specify credible interval\n\n    .. plot::\n        :context: close-figs\n\n        >>> az.plot_density([centered, non_centered], var_names=[\"mu\"], credible_interval=.5)\n\n    Shade plots and/or remove outlines\n\n    .. plot::\n        :context: close-figs\n\n        >>> az.plot_density([centered, non_centered], var_names=[\"mu\"], outline=False, shade=.8)\n\n    Specify binwidth for kernel density estimation\n\n    .. plot::\n        :context: close-figs\n\n        >>> az.plot_density([centered, non_centered], var_names=[\"mu\"], bw=.9)\n    \"\"\"\n    if not isinstance(data, (list, tuple)):\n        datasets = [convert_to_dataset(data, group=group)]\n    else:\n        datasets = [convert_to_dataset(datum, group=group) for datum in data]\n\n    var_names = _var_names(var_names, datasets)\n\n    if point_estimate not in (\"mean\", \"median\", None):\n        raise ValueError(\n            \"Point estimate should be 'mean',\" \"median' or None, not {}\".format(point_estimate)\n        )\n\n    n_data = len(datasets)\n\n    if data_labels is None:\n        if n_data > 1:\n            data_labels = [\"{}\".format(idx) for idx in range(n_data)]\n        else:\n            data_labels = [\"\"]\n    elif len(data_labels) != n_data:\n        raise ValueError(\n            \"The number of names for the models ({}) \"\n            \"does not match the number of models ({})\".format(len(data_labels), n_data)\n        )\n\n    if colors == \"cycle\":\n        colors = [\"C{}\".format(idx % 10) for idx in range(n_data)]\n    elif isinstance(colors, str):\n        colors = [colors for _ in range(n_data)]\n\n    if not 1 >= credible_interval > 0:\n        raise ValueError(\"The value of credible_interval should be in the interval (0, 1]\")\n\n    to_plot = [list(xarray_var_iter(data, var_names, combined=True)) for data in datasets]\n    all_labels = []\n    length_plotters = []\n    for plotters in to_plot:\n        length_plotters.append(len(plotters))\n        for var_name, selection, _ in plotters:\n            label = make_label(var_name, selection)\n            if label not in all_labels:\n                all_labels.append(label)\n    length_plotters = max(length_plotters)\n    rows, cols = default_grid(length_plotters, max_cols=3)\n\n    (figsize, _, titlesize, xt_labelsize, linewidth, markersize) = _scale_fig_size(\n        figsize, textsize, rows, cols\n    )\n\n    _, ax = _create_axes_grid(length_plotters, rows, cols, figsize=figsize, squeeze=False)\n\n    axis_map = {label: ax_ for label, ax_ in zip(all_labels, ax.flatten())}\n    for m_idx, plotters in enumerate(to_plot):\n        for var_name, selection, values in plotters:\n            label = make_label(var_name, selection)\n            _d_helper(\n                values.flatten(),\n                label,\n                colors[m_idx],\n                bw,\n                titlesize,\n                xt_labelsize,\n                linewidth,\n                markersize,\n                credible_interval,\n                point_estimate,\n                hpd_markers,\n                outline,\n                shade,\n                axis_map[label],\n            )\n\n    if n_data > 1:\n        for m_idx, label in enumerate(data_labels):\n            ax[0].plot([], label=label, c=colors[m_idx], markersize=markersize)\n        ax[0].legend(fontsize=xt_labelsize)\n\n    return ax\n\n\ndef _d_helper(\n    vec,\n    vname,\n    color,\n    bw,\n    titlesize,\n    xt_labelsize,\n    linewidth,\n    markersize,\n    credible_interval,\n    point_estimate,\n    hpd_markers,\n    outline,\n    shade,\n    ax,\n):\n    \"\"\"Plot an individual dimension.\n\n    Parameters\n    ----------\n    vec : array\n        1D array from trace\n    vname : str\n        variable name\n    color : str\n        matplotlib color\n    bw : float\n        Bandwidth scaling factor. Should be larger than 0. The higher this number the smoother the\n        KDE will be. Defaults to 4.5 which is essentially the same as the Scott's rule of thumb\n        (the default used rule by SciPy).\n    titlesize : float\n        font size for title\n    xt_labelsize : float\n       fontsize for xticks\n    linewidth : float\n        Thickness of lines\n    markersize : float\n        Size of markers\n    credible_interval : float\n        Credible intervals. Defaults to 0.94\n    point_estimate : str or None\n        'mean' or 'median'\n    shade : float\n        Alpha blending value for the shaded area under the curve, between 0 (no shade) and 1\n        (opaque). Defaults to 0.\n    ax : matplotlib axes\n    \"\"\"\n    if vec.dtype.kind == \"f\":\n        if credible_interval != 1:\n            hpd_ = hpd(vec, credible_interval)\n            new_vec = vec[(vec >= hpd_[0]) & (vec <= hpd_[1])]\n        else:\n            new_vec = vec\n\n        density, xmin, xmax = _fast_kde(new_vec, bw=bw)\n        density *= credible_interval\n        x = np.linspace(xmin, xmax, len(density))\n        ymin = density[0]\n        ymax = density[-1]\n\n        if outline:\n            ax.plot(x, density, color=color, lw=linewidth)\n            ax.plot([xmin, xmin], [-ymin / 100, ymin], color=color, ls=\"-\", lw=linewidth)\n            ax.plot([xmax, xmax], [-ymax / 100, ymax], color=color, ls=\"-\", lw=linewidth)\n\n        if shade:\n            ax.fill_between(x, density, color=color, alpha=shade)\n\n    else:\n        xmin, xmax = hpd(vec, credible_interval)\n        bins = range(xmin, xmax + 2)\n        if outline:\n            ax.hist(vec, bins=bins, color=color, histtype=\"step\", align=\"left\")\n        if shade:\n            ax.hist(vec, bins=bins, color=color, alpha=shade)\n\n    if hpd_markers:\n        ax.plot(xmin, 0, hpd_markers, color=color, markeredgecolor=\"k\", markersize=markersize)\n        ax.plot(xmax, 0, hpd_markers, color=color, markeredgecolor=\"k\", markersize=markersize)\n\n    if point_estimate is not None:\n        if point_estimate == \"mean\":\n            est = np.mean(vec)\n        elif point_estimate == \"median\":\n            est = np.median(vec)\n        ax.plot(est, 0, \"o\", color=color, markeredgecolor=\"k\", markersize=markersize)\n\n    ax.set_yticks([])\n    ax.set_title(vname, fontsize=titlesize, wrap=True)\n    for pos in [\"left\", \"right\", \"top\"]:\n        ax.spines[pos].set_visible(False)\n    ax.tick_params(labelsize=xt_labelsize)\n", "path": "arviz/plots/densityplot.py"}]}