carlosgguil
carlosgguil

Reputation: 33

Python 3 histogram: how to get counts and bins with plt.hist(), but without displaying the histogram in screen?

I have a set of data from which I need to extract information. The best way to do this is through a histogram: I would like to obtain a For this purpose, I use the function matplotlib.pyplot.hist() which allows me to extract the number of counts n and the bins bins. I use the function as follows:

import matplotlib.pyplot as plt
import pickle

with open('variables/dataHistogram', 'rb') as f:
    data= pickle.load(f)

nBins = 10
n, bins, patches = hist(np.sort(data), nBins, rwidth=0.9, normed = False)

I can successfully retrieve the data. My only problem is that, with this method, the histogram is always displayed. And for my purposes, I do not want it to be displayed. Is there a way in which I can extract the data without displaying the histogram ?

As additional information, I am using Spyder for running my code and I am working in Python 3.

Thanks in advance.

Upvotes: 3

Views: 13174

Answers (2)

RGMyr
RGMyr

Reputation: 301

Instead of plt.hist, you can use numpy.histogram. Example:

>>> import numpy as np
>>> x = np.random.randint(0, 5, size=10)
>>> x
array([3, 2, 0, 2, 1, 0, 2, 0, 0, 3])
>>> counts, bin_edges = np.histogram(x, bins=3)
>>> counts
array([4, 1, 5])
>>> bin_edges
array([0., 1., 2., 3.])

Upvotes: 6

Karl Anka
Karl Anka

Reputation: 2869

You can use numpy for this (docs).

import numpy as np

x = np.random.randint(0,10,(100))

n, bins = np.histogram(x, bins=10)

Upvotes: 0

Related Questions