skend skend - 1 year ago 87
Python Question

seaborn tsplot: legend colors are faded

In my seaborn

tsplot
the colors don't match the lines drawn:

Colors don't match the lines drawn.

for item in item_list:
sns.tsplot(get_data(), color=get_color(), legend=True)

sns.plt.legend(labels=item_list)
sns.plt.show()


I read the sns.tsplot and plt.legend documentation pages and can't think why this is happening.

Answer Source

The tsplot adds some regions with low alpha around the lines. Even if they are not visible (because a single line is plotted) they find their way into the legend.

A workaround is to get the lines from the plot directly:

h = plt.gca().get_lines()
plt.legend(handles=h, labels=item_list)

Complete example:

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

item_list = list("ABXY")

get_data = lambda : np.random.rand(10)
get_color = lambda : "#" + "".join(np.random.choice(list("02468acef"), size=6))

for item in item_list:
    sns.tsplot(get_data(), color=get_color())

h = plt.gca().get_lines()
plt.legend(handles=h, labels=item_list)

plt.show()

enter image description here

Let me just mention that there seems to be no reason to use a tsplot anyways in this case. A simple line plot (plt.plot) is sufficient and has less potential of confusion. The blow code produces exactly the same output as the above.

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

item_list = list("ABXY")

get_data = lambda : np.random.rand(10)
get_color = lambda : "#" + "".join(np.random.choice(list("02468acef"), size=6))

for item in item_list:
    plt.plot(get_data(), color=get_color(), label=item)

plt.legend()
plt.show()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download