Skip to content Skip to sidebar Skip to footer

Line Color As A Function Of Column Values In Pandas Dataframe

I am trying to plot two columns of a pandas dataframe against each other, grouped by a values in a third column. The color of each line should be determined by that third column, i

Solution 1:

Looks like seaborn is applying the color intensity automatically based on the value in hue..

import pandas as pd 
from matplotlib import pyplot as plt

df = pd.DataFrame({'x': [0.1,0.2,0.3,0.1,0.2,0.3,0.1,0.2,0.3,0.1,0.2,0.3],'y':[1,2,3,2,3,4,4,3,2,3,4,2], 'colors':[0.3,0.3,0.3,0.7,0.7,0.7,1.3,1.3,1.3,1.5,1.5,1.5]})

import seaborn as sns

sns.lineplot(data = df, x = 'x', y = 'y', hue = 'colors')

Gives:

plot

you can change the colors by adding palette argument as below:

import seaborn as sns

sns.lineplot(data = df, x = 'x', y = 'y', hue = 'colors', palette = 'mako')
#more combinations : viridis, mako, flare, etc.

gives:

mako color palette

Edit (for colormap):

based on answers at Make seaborn show a colorbar instead of a legend when using hue in a bar plot?

import seaborn as sns

fig = sns.lineplot(data = df, x = 'x', y = 'y', hue = 'colors', palette = 'mako')

norm = plt.Normalize(vmin = df['colors'].min(), vmax = df['colors'].max())
sm = plt.cm.ScalarMappable(cmap="mako", norm = norm)
fig.figure.colorbar(sm)
fig.get_legend().remove()
plt.show()

gives..

enter image description here

Hope that helps..

Solution 2:

Complementing to Prateek's very good answer, once you have assigned the colors based on the intensity of the palette you choose (for example Mako):

plots = sns.lineplot(data = df, x = 'x', y = 'y', hue = 'colors',palette='mako')

You can add a colorbar with matplotlib's function plt.colorbar() and assign the palette you used:

sm = plt.cm.ScalarMappable(cmap='mako')
plt.colorbar(sm)

After plt.show(), we get the combined output:

enter image description here

Post a Comment for "Line Color As A Function Of Column Values In Pandas Dataframe"