0

I am trying to plot a line chart that shows the mean value for each point in time in a dataset (say you observe 100 datapoints for each day and plot the mean for each day) - this part is easy.

What I cannot figure out to do is how to add the distribution of observed values as a vertical histogram for each timestep. Because it may be a bit hard to describe, I made a pro-level paint drawing of the desired output:

enter image description here

#Data is in x, rows are observations, columns are timesteps
import numpy as np
import matplotlib.pyplot as plt
x = np.random.rand(100,10) + np.arange(0,10)/100
plt.plot(np.mean(x,axis=0))

plt.figure()
for i in range(x.shape[1]):
    plt.hist(x[:,i], label="i")

So I can easily plot the mean and I can also easily plot the histograms, but I am struggling to combine them both into the same graph. I considering using violin plots, but didn't make any headway there either. Any help is much appreciated.

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
seulberg1
  • 955
  • 1
  • 7
  • 19
  • You might want to try a violin plot https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.violinplot.html – Matt Pitkin Oct 28 '22 at 15:26
  • Also available in seaborn https://seaborn.pydata.org/generated/seaborn.violinplot.html – Matt Pitkin Oct 28 '22 at 15:27
  • I'm inclined to close this question as duplicates of https://stackoverflow.com/q/63156008/7758804, https://stackoverflow.com/q/65423023/7758804, https://stackoverflow.com/q/67975303/7758804 – Trenton McKinney Oct 28 '22 at 16:22

1 Answers1

1

I'm not really sure what you're going for, but is something like this what you're after? Of course something isn't correct about the placement of the curves, but perhaps it's close-ish to what you want.

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

x = np.random.rand(100,10) + np.arange(0,10)/100

fig, ax = plt.subplots()

ax.plot(np.mean(x,axis=0))

for i in range(x.shape[1]):
    kde = gaussian_kde(x[:,i])
    y = np.linspace(0, 1, 20)
    ax.plot(-kde(y)+i, y)

enter image description here

K. Shores
  • 875
  • 1
  • 18
  • 46