Gabriele
Gabriele

Reputation: 959

How to stack multiple histograms in a single figure in Python?

I have a numpy array with shape [30, 10000], where the first axis is the time step, and the second contains the values observed for a series of 10000 variables. I would like to visualize the data in a single figure, similar to this: enter image description here

that you can find in the seaborn tutorial here. Basically, what I would like is to draw a histogram of 30/40 bins for each of the 30 temporal steps, and then - somehow - concatenate these histogram to have a common axis and plot them in the same figure.

My data look like a gaussian that moves and gets wider in time. You can reproduce something similar using the following code:

mean = 0.0
std = 1.0

data = []
for t in range(30):
    mean = mean + 0.01
    std = std + 0.1
    data.append(np.random.normal(loc=mean, scale=std, size=[10000]))

data = np.array(data)

A figure similar to the picture showed above would be the best, but any help is appreciated!

Thank you, G.

Upvotes: 2

Views: 358

Answers (1)

Jody Klymak
Jody Klymak

Reputation: 5932

Use histogram? You could do this with np.hist2d, but this way is a little clearer...

import matplotlib.pyplot as plt
import numpy as np

data = np.random.randn(30, 10000)

H = np.zeros((30, 40))
bins = np.linspace(-3, 3, 41)
for i in range(30):
    H[i, :], _ = np.histogram(data[i, :], bins)
fig, ax = plt.subplots()
times = np.arange(30) * 0.1
pc = ax.pcolormesh(bins, times, H)
ax.set_xlabel('data bins')
ax.set_ylabel('time [s]')
fig.colorbar(pc, label='count')

enter image description here

Upvotes: 3

Related Questions