user12441225
user12441225

Reputation:

Python plotting from for loop

How do I plot the aqr[i] values on the y-axis and the [30,60] interval on the x-axis?

I have tried the following code:

arr = np.random.randint(100, size=1000)  
arq = np.zeros(31)  

for i in range(31):
    for num in arr:
        if num == 30+i :
            arq[i] += 1
    plt.plot (arq[i])  #this line outputs an empty figure

Another version of the code I tried to get it to plot correctly is:

arr = np.random.randint(100, size=1000)  
arq = np.zeros(31) 

for i in range(31):
    for num in arr:
        for j in range (30, 61):
             if num == j+i :
            arq[i] += 1
    plt.plot (arq[i], j) 

However, the above snippet of code crashes.

Upvotes: 2

Views: 108

Answers (2)

Ali Ismaeel
Ali Ismaeel

Reputation: 381

You are trying to plot from inside the loop, I think you need to plot the data after the construction of the arq array:

arr = np.random.randint(100, size=1000)  
arq = np.zeros(31)  

for i in range(31):
    for num in arr:
        if num == 30+i :
            arq[i] += 1

plt.rcParams["figure.figsize"] = (10,5)
plt.plot(arq,'o')

output

In this output plot 0 means 30 , 1 means 31 , etc..

Upvotes: 1

tdy
tdy

Reputation: 41437

If I understand correctly, pull the plot() command outside the loop and plot the whole arq array at once:

np.random.seed(123)
arr = np.random.randint(100, size=1000)
arq = np.zeros(31)
for i in range(31):
    for num in arr:
        if num == 30+i:
            arq[i] += 1
plt.plot(range(30,61), arq)

arq plot


Note that you can also do this with hist():

np.random.seed(123)
arr = np.random.randint(100, size=1000)
arq = np.zeros(31)
plt.hist(arr, bins=range(30, 61))

arq histogram

Upvotes: 0

Related Questions