Search code examples
pythonloopsgraph

Python: Multiple Graphs For Loop


My data set has 5 ClientIDs, I would like to produce a graph for each ClientID

I have been able to iterate through my key and create five graphs however, they are including all the data and not just that of the client ID

# group by "X" column
clients = dfT1.groupby('ClientID')
 
# extract keys from groups
keys = clients.groups.keys()

for i in keys:
    dfT1[:].plot(x='Dates', y=['DWLTActual', 'Weight'], figsize=(10,5), grid=True)
    plt.show()

Output

Example of the 5 graphs

Expected Output

Example of one of the client graphs


Solution

  • Can you check it like this. I executed with sample data locally on my computer and it worked.

    You need to filter the client data first before plotting.

    clients = dfT1.groupby('ClientID')
    
    # Extract keys from groups
    keys = clients.groups.keys()
    
    
    for client_id in keys:
        # Filter data for the current client ID
        client_data = clients.get_group(client_id)
    
        # Plot the filtered data
        client_data.plot(x='Dates', y=['DWLTActual', 'Weight'], figsize=(10, 5), grid=True)
    
        # Set the title of the graph as the ClientID
        plt.title('ClientID: {}'.format(client_id))
    
        # Show the plot
        plt.show()