user9185511
user9185511

Reputation: 814

Matplotlib - plotting grouped values with a for loop

I'm trying to plot a graph grouped by column values using a for loop without knowing the number of unique values in that column.

You can see sample code below (without a for loop) and the desired output.

I would like that each plot will have different color and marker (as seen below).


This is the code:

import pandas as pd
from numpy import random

df = pd.DataFrame(data = random.randn(5,4), index = ['A','B','C','D','E'],
columns = ['W','X','Y','Z'])

df['W'] = ['10/01/2018 12:00:00','10/03/2018 13:00:00',
           '10/03/2018 12:30:00','10/04/2018 12:05:00',
           '10/08/2018 12:00:15']

df['W']=pd.to_datetime(df['W'])

df['Entity'] = ['C201','C201','C201','C202','C202']

print(df.head()) 

fig, ax = plt.subplots()
df[df['Entity']=="C201"].plot(x="W",y="Y",label='C201',ax=ax,marker='x')
df[df['Entity']=="C202"].plot(x="W",y="Y",label='C202',ax=ax, marker='o')

This is the output:

enter image description here

Upvotes: 2

Views: 253

Answers (1)

Sheldore
Sheldore

Reputation: 39052

You can first find out the unique values of your df['Entity'] and then loop over them. To generate new markers automatically for each Entity, you can define an order of some markers (let's say 5 in the answer below) which will repeat via marker=next(marker).


Complete minimal answer

import itertools
import pandas as pd
from numpy import random
import matplotlib.pyplot as plt

marker = itertools.cycle(('+', 'o', '*', '^', 's')) 
df = pd.DataFrame(data = random.randn(5,4), index = ['A','B','C','D','E'],
columns = ['W','X','Y','Z'])

df['W'] = ['10/01/2018 12:00:00','10/03/2018 13:00:00',
           '10/03/2018 12:30:00','10/04/2018 12:05:00',
           '10/08/2018 12:00:15']

df['W']=pd.to_datetime(df['W'])

df['Entity'] = ['C201','C201','C201','C202','C202']

fig, ax = plt.subplots()

for idy in np.unique(df['Entity'].values):
    df[df['Entity']==idy].plot(x="W",y="Y", label=idy, ax=ax, marker=next(marker))

plt.legend()
plt.show()

enter image description here

Upvotes: 1

Related Questions