3

Is there any way to get the values in "x" and "y" of a histogram without graphing** it? I use the function below many times (in each loop) in my code, and I noticed that my code gets slower and slower in each loop.

** I am not sure if what it does internally is to graph but I know that the slowness in my code is related to the function "plt.hist" despite using plt.close(). Thank you.

# a is a list
def function_hist(a, ini, final):

    # 12 bins
    bins = np.linspace(ini, final, 13)
    weightsa = np.ones_like(a)/float(len(a))
    y, x, _ = plt.hist(a, bins, weights = weightsa)
    plt.close()
user140259
  • 450
  • 2
  • 5
  • 16
  • 2
    https://stackoverflow.com/questions/17348548/any-way-to-create-histogram-with-matplotlib-pyplot-without-plotting-the-histogra – Pavel Dec 10 '17 at 23:10
  • Possible duplicate of [Any way to create histogram with matplotlib.pyplot without plotting the histogram?](https://stackoverflow.com/questions/17348548/any-way-to-create-histogram-with-matplotlib-pyplot-without-plotting-the-histogra) – John Szakmeister Dec 11 '17 at 00:08

1 Answers1

10

Use numpy.histogram

You can modify your function as below

# a is a list
def function_hist(a, ini, final):

    # 12 bins
    bins = np.linspace(ini, final, 13)
    weightsa = np.ones_like(a)/float(len(a))
    hist = np.histogram(np.array(a), bins, weights = weightsa)
Umang Gupta
  • 15,022
  • 6
  • 48
  • 66