KDE plot does not show up on Matplotlib axis

Hello,

I am attempting to use the KDE plot on an axis pre-defined with a Matplotlib subplots object. However, the KDE figure does not show up on the axis:

rng = np.random.default_rng()
data = rng.multivariate_normal([2, 2], [[1, 0.4], [0.4, 0.8]], 1000000)
fig, ax = plt.subplots(1, 1, figsize=(3, 3))
axs[0] = az.plot_kde(data[:, 0], data[:, 1], ax=axs[0], hdi_probs=[0.393, 0.865, 0.989], contourf_kwargs={"cmap": "Blues"})

The plot works fine without attempting to put it on a pre-defined axis:

rng = np.random.default_rng()
data = rng.multivariate_normal([2, 2], [[1, 0.4], [0.4, 0.8]], 1000000)
ax = az.plot_kde(data[:, 0], data[:, 1], hdi_probs=[0.393, 0.865, 0.989], contourf_kwargs={"cmap": "Blues"})

I know that this may seem like a duplicate of this question. However, for that person the issue seemed to be that they had az.rcParams["plot.matplotlib.show"] = True (not sure why this would cause an issue). However, my issue persists whether or not I have az.rcParams["plot.matplotlib.show"] set to True, or False. For context, I am running this in a VSCode notebook.

Thanks so much for any insight you can offer!

In case this is useful for anyone: I found the solution, which is to add the show=True argument to plot_kde(). I am not sure why this is different than setting show in rcParams to True, but it works.

I suspect your problem might also have been related to the fact that you are creating a single axis and trying to index into it here:

fig, ax = plt.subplots(1, 1, figsize=(3, 3))
axs[0] = az.plot_kde(data[:, 0], data[:, 1], ax=axs[0], hdi_probs=[0.393, 0.865, 0.989], contourf_kwargs={"cmap": "Blues"})

This will first create an empty axis and then throw an error

TypeError: 'Axes' object is not subscriptable

and if you do not notice the error, all you will be seeing is an empty axis. When I changed this to

fig, ax = plt.subplots(1, 1, figsize=(3, 3))
ax = az.plot_kde(data[:, 0], data[:, 1], ax=ax, hdi_probs=[0.393, 0.865, 0.989], 
                 contourf_kwargs={"cmap": "Blues"})

it works fine without having to supply show=True. What you did in the second piece of code also works because you are not indexing into the axis.

1 Like