Home > OS >  How do I plot histograms on top of a function with matplotlib?
How do I plot histograms on top of a function with matplotlib?

Time:03-09

image of my problem

As I hope you can see from the image, I have a bundle of functions of 'x'. For each input point, there is a distribution of these functions, thus average (AVG) and variance (VAR). I would like to plot histograms on top of the graph of the functions like shown on the right of the image using matplotlib if possible, but HOW?

CodePudding user response:

You can use scipy.stats.gausian_kde to calculate a kernel density estimation and draw those vertically.

Here is some example code using 20 curves:

from matplotlib import pyplot as plt
import numpy as np
from scipy.stats import gaussian_kde

N = 100
K = 20
ys = np.random.normal(0.1, 1, (N, K)).cumsum(axis=0)
ys -= ys.min(axis=0, keepdims=True)
x = np.arange(N)
plt.plot(x, ys, color='cornflowerblue', alpha=0.2)
plt.plot(x, ys.mean(axis=1), color='navy', lw=3, label='mean y')
for i in range(10, len(x), 20):
    yi = ys[i, :]
    ymin, ymax = yi.min(), yi.max()
    y_range = ymax - ymin
    ymin -= y_range * 0.1
    ymax  = y_range * 0.1
    kde = gaussian_kde(yi, bw_method=y_range / 100)
    plt.vlines(x[i], ymin, ymax, ls=':', color='black')
    y = np.linspace(ymin, ymax, 200)
    kde_y = kde(y)
    kde_y *= - 10 / kde(y).max()
    kde_y  = x[i]
    plt.plot(kde_y, y, color='black')
    plt.fill_betweenx(y, x[i], kde_y, color='black', alpha=.2)
plt.xticks(x[::10])
plt.show()

multiple curves with mean and kdes at certain x positions

  • Related