Home > Net >  Plot values of a column depending on another with legends
Plot values of a column depending on another with legends

Time:10-11

I have a dataframe as shown:

df = 

     col_1   val_1
0    4.0     0.89
1    4.0     0.56
2    6.0     0.7
3    6.0     0.23
4    78.0    0.8
5    78.0    0.45
6    81.0    0.90
7    81.0    0.23

I want to plot the values in val_1 in different colors depending on values in col_1. I want labels to be distinctly present for the values in col_1.

I did the following:

df.plot.scatter('val_1', 'col_1', c='col_1', colormap='jet')

This does not distinctly represent the difference for the values 4.0 and 6.0 and for values 78.0 and 81.0.

Is there a better way to represent this with distinct colours and labels?

CodePudding user response:

As the values in your col_1 are very close, the jet colormap will assign them close together. If you want to keep different equally varying colors, then you can update the code as below. This will assign 8 equally spaced colors within the jet colormap for the points. Hope this is what you are looking for.

import matplotlib.cm as cm
import itertools

#df.plot.scatter('val_1', 'col_1', c='col_1', colormap='jet')
colors = iter(cm.jet(np.linspace(0, 1, len(df))))
for i, row in df.iterrows():
    plt.scatter(row['val_1'], row['col_1'], c=next(colors).reshape(1,-1))

strong text

enter image description here

CodePudding user response:

you can make the col1 values categorical.

df['col_1']=pd.Categorical(df['col_1'])
df.plot.scatter('val_1', 'col_1', c='col_1', colormap='jet')

enter image description here

  • Related