Histogram matplotlib from arrays

18,777

You can make a histogram in matplotlib using matplotlib.pyplot.hist. Given the code in the question, where you want the values in a to be the frequencies for values in 2400 through 2500, this could be as simple as doing:

plt.hist(range(2400, 2501), weights=a[0][0])
plt.show()

Doing that generates a histogram from a with the default ten bins, as shown below.

Histogram with ten bins.

There is a little strangeness there, however, because a has 101 values (meaning the range plotted is 2400 through 2500, inclusive), so the last bin gets the frequency counts for eleven values, while the other bins get frequency counts for ten values. You can give each value its own bin with the following.

plt.hist(range(2400, 2501), weights=a[0][0], bins=101)
plt.show()

That generates the image below.

Histogram with 101 bins.

Share:
18,777
Thomas
Author by

Thomas

Learning python basics in free time.

Updated on June 30, 2022

Comments

  • Thomas
    Thomas almost 2 years

    I have two arrays:

    For example:

    a=[1, 2, 3, 4]
    
    b=[10, 20, 30, 40]
    

    And from those number I need to plot histogram, I known that is easy to plot curve with coordinates likes this (1,10), (2, 20) and etc. But how to plot histogram from arrays. Currently I am stuck with option to draw histogram. Any suggestion would be good.

    import matplotlib.pyplot as plt
    import numpy as np
    
    a = [([97, 99, 99, 96, 97, 98, 99, 97, 99, 99, 96, 97, 99, 99, 95,
           98, 99, 97, 97, 98, 97, 96, 98, 98, 98, 98, 98, 98, 96, 98, 98, 98, 98,
           98, 98, 96, 97, 97, 97, 97, 97, 96, 96, 97, 97, 96, 95, 97, 96, 97, 96, 97,
           96, 95, 96, 97, 95, 95, 93, 93, 92, 93, 93, 95, 95, 94, 93, 94, 94, 95, 95, 95,
           95, 96, 96, 95, 96, 96, 96, 96, 94, 95, 90, 95, 95, 95, 95,
           95, 88, 94, 94, 93, 95, 95, 94, 95, 95, 95, 95, 95, 93],)]
    
    for item in a[0]:
        s = item
    
    lengths = len(s)
    s2 = [s[x:x+9] for x in xrange(0, len(s), 9)]
    print s2.index(min(s2))
    
    test = 2400+int(lengths)
    xaxis=range(2400,test)
    yaxis=s
    

    Below is image example x axis is value from 2400- 2500 and y axis is values from some kind of array.

    enter image description here

  • Thomas
    Thomas over 12 years
    It shows but not really what I need. I need that x axis would be values from 2400 to 2500 and y axis (height of histogram would be from array a).
  • Thomas
    Thomas over 12 years
    Added image how it should look.