pandas how to have different color line graph

by jaykodeveloper   Last Updated September 12, 2018 04:26 AM

I have a dataframe,

index block array_size  time
0   2   100 0.102710
1   2   1000    0.356194
2   2   10000   2.884903
3   2   100000  28.484935
4   2   1000000 293.656645
5   2   8000000 91286.889516
6   4   100 0.103323
7   4   1000    0.347484
8   4   10000   2.799290
9   4   100000  27.3598

enter image description here

I want to have different color for different value of block (2 and 4. second column)
My code for this plot is df.plot(x='array_size', y='time') How can I have different color for each variables ?



Answers 2


Get the two dataframes for each block

block_2=df[df["block"]==2]
block_4=df[df["block"]==4]

And plot separately

import matplotlib.pyplot as plt 
plt.plot(block_2["array_size"],block_2["time"],"r") #color red
plt.plot(block_4["array_size"],block_4["time"],"g") #color green
plt.show()
Sruthi V
Sruthi V
September 12, 2018 04:18 AM

You can either just plot them each separately with a simple groupby, or if you are willing to use seaborn that will allow you to specify a column for hue

import pandas as pd
import seaborn as sns

fig, ax = plt.subplots(figsize=(8,4))

for idx, gp in df.groupby('block'):
    gp.plot(x='array_size', y='time', ax=ax, label=idx)
plt.show()

enter image description here

With seaborn (at least 0.9) you can just do:

sns.lineplot(data=df, x='array_size', y='time', hue='block')

Since you say you have many 'blocks' you probably need to change to a color map instead of the normal 6 or so colors in the default cycler.

ALollz
ALollz
September 12, 2018 04:25 AM

Related Questions


Custom legend in Pandas bar plot (matplotlib)

Updated April 15, 2015 03:15 AM