Grid chart question - Traffic dataset

Screen Link: Learn data science with Python and R projects

My Code:

import pandas as pd
import matplotlib.pyplot as plt

traffic = pd.read_csv('traffic_sao_paulo.csv', sep=';')
traffic['Slowness in traffic (%)'] = traffic['Slowness in traffic (%)'].str.replace(',', '.')
traffic['Slowness in traffic (%)'] = traffic['Slowness in traffic (%)'].astype(float)

days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
traffic_per_day = {}
for i, day in zip(range(0, 135, 27), days):
    each_day_traffic = traffic[i:i+27]
    traffic_per_day[day] = each_day_traffic
    
plt.figure(figsize=(10,12))

for i, day in zip(range(1,6), days):
    plt.subplot(3, 2, i)
    plt.plot(traffic_per_day[day]['Hour (Coded)'],
        traffic_per_day[day]['Slowness in traffic (%)'])
    plt.title(day)
    plt.ylim([0,25])    


for day in days:    
    plt.subplot(3, 2, 6)
    plt.plot(traffic_per_day[day]['Hour (Coded)'], 
             traffic_per_day[day]['Slowness in traffic (%)'],
            label=day)
    plt.ylim([0,25])
    
plt.legend()    
plt.show()

The hints mentioned it needs to put plt.subplot(3, 2, 6) out of the for loop. It seems make sense as it needs to create the plot first. but it still work if i put plt.subplot(3, 2, 6) inside for loop. Can you explain more please?

Hi @ipngasi,

This piece of code plt.subplot(3, 2, 6) is used to call the corresponding subplot, for Python to understand where exactly to add the next plot (i.e., not to re-write the already existing plot there, but to add a new one). If to forget about for-loops, let’s imagine you have to create 2 different line plots on the 1st subplot of a grid of 3 rows and 2 columns. You can use:

plt.subplot(3, 2, 1)
plt.plot(traffic['Slowness in traffic (%)'])
plt.subplot(3, 2, 1)
plt.plot(traffic['Hour (Coded)'])

or this:

plt.subplot(3, 2, 1)
plt.plot(traffic['Slowness in traffic (%)'])
plt.plot(traffic['Hour (Coded)'])

the result will be the same: 2 line plots on the same subplot. The second piece of code, though, is better, since it’s more laconic, and there is no need (even though it’s not an error) to call the same subplot twice to add another line plot on it.

In your case, the same thing: no need to call the subplot plt.subplot(3, 2, 6) all the times you want to add a new plot on it at each iteration of your for-loop (even though it’s not an error, just a redundant work). It’s enough to call it only once, i.e. before the for-loop.