Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Seaborn multi line plot with only one line colored

I am trying to plot a multi line plot using sns but only keeping the US line in red while the other countries are in grey

This is what I have so far:

df = px.data.gapminder()
sns.lineplot(x = 'year', y = 'pop', data = df, hue = 'country', color = 'grey', dashes = False, legend = False)

But this does not change the lines to grey. I was thinking that after this, I could add in US line by itself in red.....

like image 416
TYL Avatar asked Feb 03 '26 22:02

TYL


2 Answers

You can use pandas groupby to plot:

fig,ax=plt.subplots()
for c,d in df.groupby('country'):
    color = 'red' if c=='US' else 'grey'
    d.plot(x='year',y='pop', ax=ax, color=color)

ax.legend().remove()

output:

enter image description here

To keep the original colors for a default palette, but grey out the rest, you can choose to pass color='grey' only when the condition is met:

if c in some_list:
    d.plot(...)
else:
    d.plot(..., color='grey')

Or you can define a specific palette as a dictionary:

palette = {c:'red' if c=='US' else 'grey' for c in df.country.unique()}

sns.lineplot(x='year', y='pop', data=df, hue='country', 
             palette=palette, legend=False)

Output:

enter image description here

like image 84
Quang Hoang Avatar answered Feb 05 '26 12:02

Quang Hoang


You can use the palette parameter to pass custom colors for the lines to sns.lineplot, for example:

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

df = pd.DataFrame({'year': [2018, 2019, 2020, 2018, 2019, 2020, 2018, 2019, 2020, ], 
                   'pop': [325, 328, 332, 125, 127, 132, 36, 37, 38], 
                   'country': ['USA', 'USA', 'USA', 'Mexico', 'Mexico', 'Mexico',
                               'Canada', 'Canada', 'Canada']})

colors = ['red', 'grey', 'grey']
sns.lineplot(x='year', y='pop', data=df, hue='country', 
             palette=colors, legend=False)

plt.ylim(0, 350)
plt.xticks([2018, 2019, 2020]);

red-gray lineplot

It could still be useful to have a legend though, so you may also want to consider tinkering with the alpha values (the last values in the tuples below) to highlight the USA.

red = (1, 0, 0, 1)
green = (0, 0.5, 0, 0.2)
blue = (0, 0, 1, 0.2)
colors = [red, green, blue]

sns.lineplot(x='year', y='pop', data=df, hue='country', 
             palette=colors)

plt.ylim(0, 350)
plt.xticks([2018, 2019, 2020]);

various alpha example plot

like image 42
Arne Avatar answered Feb 05 '26 12:02

Arne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!