2

See the code below. I create a plot with seaborn then I plot some other values over the same figure with plt.plot, works fine, but the plt.legend method apparently is not additive, that is, I cannot use it to label both lines in the chart, which would be 'from seaborn' and 'from plt', both associated with the proper line color.

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
mean, cov = [0, 2], [(1, .5), (.5, 1)]
data_sample, y = np.random.multivariate_normal(mean, cov, size=100).T
data_min = min(data_sample)
data_max = max(data_sample)
plot_points = [(data_min + (i/100) * (data_max-data_min)) for i in range(0, 100)]
sns.set(color_codes=True)
plt.figure()
ax = sns.kdeplot(data_sample, legend='from seaborn')
ax.plot(plot_points, y)
plt.legend(['from plt'])
plt.show()

How can I address this?

1
  • 1
    Try ax = sns.kdeplot(..., label='from seaborn'); ax.plot(..., label='from plot') and plt.legend() without parameters Commented May 26, 2020 at 17:49

1 Answer 1

2

Change legend to label and add label to plot:

ax = sns.kdeplot(data_sample, label='from seaborn')
ax.plot(plot_points, y, label='from plt')
ax.legend()

Output:

enter image description here

Sign up to request clarification or add additional context in comments.

2 Comments

As you've posted it doesn't work for me. It happened along with calling plt.legend() without parameters, as @JohanC suggested. Did you exclude the plt.legend call? If not, consider editing your answer to mention it, then I'll accept it.
I used ax.legend() instead of plt.legend(). See update. But plt.legend() also work for me. Both without any parameters.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.