Seaborn lineplot legend not showing correct line colour – plotting two pandas series on one graph

Question:

I’m trying to plot two data sets with Seaborn, this is my code.

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

sns.axes_style("ticks")

ss_data = pd.read_csv('A.csv')
ks_data = pd.read_csv('B.csv')

g = sns.lineplot(data=ks_data, x="K", y="pd", dashes=False)
sns.lineplot(data=ss_data, x="K", y="pd", dashes=False)
g.set_xticks(range(0,22,4))
plt.legend(labels=["A", "B"])
plt.savefig("test.png", dpi=500)

But this is the graph I am getting, as you can see, the legend doesn’t correctly show the line colour for B.

enter image description here

I think it’s probably due to the way that I am adding the second lineplot to the graph, but I couldn’t make it work any other way.

Asked By: redpanda2236

||

Answers:

Use the label parameter (passed to matplotlib.axes.Axes.plot()), and no need for plt.legend().

sns.lineplot(
    data=ks_data, x="K", y="pd", 
    label='A', errobar=None)
sns.lineplot(
    data=ss_data, x="K", y="pd", 
    label='B', errorbar=None)

Importantly, pass errorbar=None (or for seaborn versions prior to 0.12.0, ci=None), to turn off plotting of the confidence interval.

Answered By: BigBen

Maybe a matplotlib / seaborn version issue?
I’m not able to reproduce your graph. With some dummy data I get the expected results:

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

sns.axes_style("ticks")

data1 = {"K":[1,5,10,15,20], "pd":[2,10,20,30,40]}
data2 = {"K":[1,5,10,15,20], "pd":[1.5,9,18,16,35]}

ss_data = pd.DataFrame(data=data1)
ks_data = pd.DataFrame(data=data2)

g = sns.lineplot(data=ks_data, x="K", y="pd", dashes=False)
sns.lineplot(data=ss_data, x="K", y="pd", dashes=False)
g.set_xticks(range(0,22,4))
plt.legend(labels=["A", "B"])

enter image description here

I have seaborn == 0.11.2 and matplotlib==3.5.0

Answered By: Mat.B
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.