首页 > 解决方案 > 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.e. one color per group.

For example:

import pandas as pd
from matplotlib import pyplot as plt

fig, ax = plt.subplots()

df = pd.DataFrame({'x': [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], 'colors':[0.3,0.3,0.3,0.7,0.7,0.7,1.3,1.3,1.3]}) 

df.groupby('colors').plot('x','y',ax=ax)

Current output

If I do it this way, I end up with three different lines plotting x against y, with each line a different color. I now want to determine the color by the values in 'colors'. How do I do this using a gradient colormap?

标签: pythonpandasdataframecolorsline-plot

解决方案


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..


推荐阅读