【问题标题】:Plot over Seaborn plot and add legend绘制 Seaborn 情节并添加图例
【发布时间】:2020-05-26 17:37:29
【问题描述】:

请参阅下面的代码。我用seaborn 创建了一个图,然后我用plt.plot 在同一个图上绘制了一些其他值,工作正常,但plt.legend 方法显然不是加法,也就是说,我不能用它来标记图表,这将是 'from seaborn''from plt',两者都与正确的线条颜色相关联。

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()

我该如何解决这个问题?

【问题讨论】:

  • 试试ax = sns.kdeplot(..., label='from seaborn'); ax.plot(..., label='from plot')plt.legend() 不带参数

标签: python-3.x matplotlib seaborn


【解决方案1】:

legend更改为label并将label添加为plot

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

输出:

【讨论】:

  • 正如您发布的那样,它对我不起作用。正如@JohanC 建议的那样,它发生在不带参数的情况下调用plt.legend()。您是否排除了plt.legend 电话?如果没有,请考虑编辑您的答案以提及它,然后我会接受它。
  • 我使用了ax.legend() 而不是plt.legend()。见更新。但是plt.legend() 也为我工作。两者都没有任何参数。
猜你喜欢
  • 1970-01-01
  • 2021-02-15
  • 1970-01-01
  • 2021-03-24
  • 2019-04-15
  • 1970-01-01
  • 2018-11-29
  • 1970-01-01
  • 2017-02-09
相关资源
最近更新 更多