Loop to add more plot line

I did not understand this part of the loop start_index = i*12
end_index = (i+1)*12. Can somebody help to get it please

fig = plt.figure(figsize=(10,6))
colors = [‘red’, ‘blue’, ‘green’, ‘orange’, ‘black’]
for i in range(5):
start_index = i*12
end_index = (i+1)*12
subset = unrate[start_index:end_index]
plt.plot(subset[‘MONTH’], subset[‘VALUE’], c=colors[i])

1 Like

Hi and welcome to our community! :wave: We’d love to be able to help. Could you edit your post to provide more context (such as a link to the mission you’re working on)? Here is a guide for asking questions that will hopefully help you get a good response: Guide: How to Ask a Good Question. Thanks!

Hi, thanks for reply. this the link of the loop,. https://app.dataquest.io/m/143/multiple-plots/9/adding-more-lines

There are different ways to accomplish this mission to plot the unemployment rates on the same plot. One method is to write the code for each line separately, and it will automatically get added to the same plot. This was actually how I approached the mission at first. I’m including a sample so we can understand what’s going in the loop in the solution code:

plt.plot(unrate[0:12]['MONTH'], unrate[0:12]['VALUE'], c='red')
plt.plot(unrate[12:24]['MONTH'], unrate[12:24]['VALUE'], c='blue')
plt.plot(unrate[24:36]['MONTH'], unrate[24:36]['VALUE'], c='green')

Using a loop is a really clever way of doing the same thing without having to type out all the same code. On the first iteration, you have i=0, which will make start_index=0 and end_index=12. The color assignment will be the 0 index of the colors list (red). When it gets to the part where the graph is plotted, you will end up with plt.plot(unrate[0:12]['MONTH'], unrate[0:12]['VALUE'], c='red'), just like in my code sample. On the next iteration, i=1, so then start_index=12 and end_index=24 and the color will be ‘blue’, which will give you plt.plot(unrate[12:24]['MONTH'], unrate[12:24]['VALUE'], c='blue'). You end up with the same thing, but without repeating similar code over and over.

I hope that helps clear things up.


thank you very much for great explanation . it is clear now.

Happy to help! Please make sure to mark the solution so that other students who have a similar question can benefit!