0

I'm writing a code about plotting. I write with hardcode ways, so my code is not flexible enough.

I know can using for loop to solve the hardcode problems. But my Python ability not strong enough.

Here's my code.

df1 = df[df.cluster==0]
df2 = df[df.cluster==1]
df3 = df[df.cluster==2]

plt.scatter(df1.Age,df1['Income($)'],color='green')
plt.scatter(df2.Age,df2['Income($)'],color='red')
plt.scatter(df3.Age,df3['Income($)'],color='black')

On this case's there's have 3 cluster. If cluster = 4, then need write more. df4 = ...

Can i write a for loop, such like this

n = number of cluster
for i in range(n):
    df(random) = df[df.cluster==i]
for j in range(n):
    plt.scatter(df(n).Age,df(n)['Income($)'],color='RANDOM')

My question is write a code only a few line not using hardcode ways.

bob
  • 91
  • 1
  • 13

3 Answers3

3

If you are looking for a simple solution, this might be it. (I have reused your code sample)

n = num_of_clusters
my_colors = ['green', 'red', 'black', ...]
for i in range(n):
    df_i = df[df.cluster == i]
    plt.scatter(df_i.Age, df_i['Income($)'], color=my_colors[i])
cijad
  • 152
  • 3
2

This is a classic "groupby" operation in pandas.

Take a look at some of the posts on using groupby. You could...

  • use groupby to make groups based on the value of cluster
  • Use a for-loop to loop over the groups and...
  • plot each group in the container of groups.

Here is an example using groupby

In [57]: from matplotlib import pyplot as plt                                   

In [58]: import pandas as pd                                                    

In [59]: data = {'year':[1976, 1979, 1982, 1978, 1982], 'income':[200, 170, 100,
    ...:  50, 120], 'cluster': [1, 1, 1, 2, 2]}                                 

In [60]: df = pd.DataFrame(data)                                                

In [61]: df                                                                     
Out[61]: 
   year  income  cluster
0  1976     200        1
1  1979     170        1
2  1982     100        1
3  1978      50        2
4  1982     120        2

In [62]: for label, df in df.groupby('cluster'): 
    ...:     plt.plot(df['year'], df['income'], label=label) 
    ...:                                                                        

In [63]: plt.legend()                                                           
Out[63]: <matplotlib.legend.Legend at 0x7fe792601e80>

In [64]: plt.show() 

produces:

enter image description here

AirSquid
  • 10,214
  • 2
  • 7
  • 31
2

One possibility:

colors = ['green', 'red', 'black']

for i in range(3):
    df_temp = df[df.cluster==i]
    plt.scatter(df_temp.Age, df_temp['Income($)'], color=colors[i])
Anis R.
  • 6,656
  • 2
  • 15
  • 37