简体   繁体   中英

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.

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

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 图


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直方图

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM