2

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.

0

2 Answers 2

1

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..

Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

@Kareena you're welcome! by the way you can also use hist() to avoid looping

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.