Plot_kde in 2D with hdi contours only

Hi! I want to use the az.plot_kde for 2D data, but I’d like to simplify the default aesthetics, so that all that is plotted are contours for selected hdi_probs. Could You please tell me if and how could I do that? Also, how do I control “ruggedness” of the KDE approximation? The bw arg doesn’t seem to be doing anything for me.

As a point of reference, below’s an example of a plot. I’d like to have only contours of the colourful pancakes, and not the pancakes themselves :slight_smile:

import numpy as np
from scipy import stats

rng = np.random.default_rng(0)
x, y = stats.multivariate_normal(mean=[0.0, 0.0], cov=[[1, 0.0], [0.0, 1]]).rvs(1_000, random_state=rng).T

fig, axs = plt.subplots(1, 2, figsize=(8, 4))

kwargs = dict(
    hdi_probs=[0.25, 0.5, 0.75],
    contour_kwargs={"alpha": 0.0})

az.plot_kde(
    x, y,
    bw=0.01,
    ax=axs[0],  
    **kwargs)
axs[0].set_title("bw=0.01")

az.plot_kde(
    x, y,
    bw=100,
    ax=axs[1],  
    **kwargs)
axs[1].set_title("bw=100")

for ax in axs:
    ax.set_xlim(-2, 2)
    ax.set_ylim(-2, 2)
    ax.set_aspect("equal")

cc @OriolAbril

It is a bit tricky. You need to combine fill_last=True with alpha=0 in contourf_kwargs. If you use for example:

kwargs = dict(
    hdi_probs=[0.25, 0.5, 0.75],
    fill_last=True,
    contour_kwargs={"cmap": "viridis", "colors": None},
    contourf_kwargs={"alpha": 0.0}
)
az.plot_kde(x, y, **kwargs)

you will get the following plot:

You can remove the contour_kwargs part if you want all lines to have the same color, the default is gray lines, or change color="red" and remove cmap key for lines to be red. If you were to remove the fill_last=True you’d get filled contours again as that goes over the generated contourf objects after they are plotted and overrides their alpha values so all but last contour fills have alpha=1, the last has alpha=0.

I am afraid the bandwidth can’t be modified in the 2d KDE. You can see the function that computes the 2d KDE and it doesn’t take any bw related argument: arviz/arviz/stats/density_utils.py at 35fa479d617aa82dbe005af12fab6b37146e8c5b · arviz-devs/arviz · GitHub.