Denis  Korzhenkov
Denis Korzhenkov

Reputation: 383

Plot precomputed charts in several axes

Some matplotlib or seaborn functions need lots of time for computing, e.g. kdeplot.

I'd like to create plt.subplots(2, 3), put the same kde plot to all the six axes and then add other stuff to every axis independently. Of course, I wouldn't like to compute kdeplot 6 times.

How is it possible to avoid multiple computing?

Upvotes: 1

Views: 110

Answers (1)

Diziet Asahi
Diziet Asahi

Reputation: 40707

It would help to know more about the kind of data you're working with, and the resulting kdeplot. Basically, seaborn is a helper library to produce nice plots, but it relies on other libraries to do the heavy lifting. So I think the easiest way to solve your problem is to figure out how seaborn calculates the KDE, do the calculation yourself, and then plot the results in your subplots.

For example:

mean, cov = [0, 2], [(1, .5), (.5, 1)]
x, y = np.random.multivariate_normal(mean, cov, size=50).T
ax = sns.kdeplot(x, shade=True, color="r")

enter image description here

Looking at the code for kdeplot(), I see that it uses statsmodel (or scipy) to compute the KDE. It even uses a small helper function, which I could use:

fig, axs = plt.subplots(2, 3)

# adjust parameters as you would calling sns.kdeplot
kde_x,kde_y = sns.distributions._statsmodels_univariate_kde(x, kernel="gau",
            bw="scott", gridsize=100, cut=3, clip=(-np.inf, np.inf), 
            cumulative=False)

for ax in axs.flatten():
    # adjust parameters to match your desired output
    ax.plot(kde_x,kde_y)
    ax.fill_between(kde_x, 0, kde_y, alpha=0.25, clip_on=True, zorder=1)

enter image description here

Upvotes: 1

Related Questions