Peter
Peter

Reputation: 23

How to make a histogram of values in Python

I am writing a code in Python (posted below) and would like to generate a histogram displaying frequency of y-values within a bin of width = 1. For example, how many y's are between 6-7, 7-8, etc. However, the plot only contains the final value of y. Does anyone know how I can include all the y-values? Thank you in advance!

import numpy as np
import matplotlib.pyplot as plt

N = 10

for i in range(0,N):
    x = 1 + np.random.random()
    print("x = ", x)
    y = 2*(1 + 2*x)
    print("y = ", y)
    z = 4*y
    print("z = ", z)

h = [y]
plt.hist(h, bins = 10)
plt.show()

Upvotes: 0

Views: 119

Answers (2)

Colas
Colas

Reputation: 2076

Similar to @roadrunner66's answer, but using numpy arrays directly instead of looping over a list:

import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

N = 10
x = 1 + np.random.random(N)
y = 2*(1 + 2*x)

plt.hist(y, bins=4, range=(6,10))
plt.show()

enter image description here

Upvotes: 0

roadrunner66
roadrunner66

Reputation: 7941

To make a list, generate an empty list before your loop. Then append list items during the loop.

import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

#use print commands to check the type and content of your variables

N = 10
ys=[]  # empty list
for i in range(0,N):
    x = 1 + np.random.random()
    y = 2*(1 + 2*x)
    ys.append(y)


plt.hist(ys, bins = 10)
plt.show()

enter image description here

Upvotes: 2

Related Questions