多个 seaborn 点图未在图例上显示正确的颜色

Multiple seaborn pointplots not showing the right color on the legend

我有一个三点图,我正在尝试绘制图表并显示图例。颜色与图中标出的颜色不匹配。我尝试使用 的解决方案,但没有用。

这是我使用的代码:

fig, ax = plt.subplots()
a = sns.pointplot(x=l[1:], y = np.exp(model_m.params[1:]), label = 'factor',
              ax = ax, color = 'green')

b = sns.pointplot(x=l[1:], y = np.exp(model_m.conf_int()[1:][:,1]), 
              ax = ax, label = 'conf_int+', color = 'red')

c = sns.pointplot(x=l[1:], y = np.exp(model_m.conf_int()[1:][:,0]), 
              ax = ax, label = 'conf_int-', color = 'blue')
plt.title('Model M Discrete')
ax.legend(labels = ['factor', 'conf_inf+', 'conf_inf-'],
           title = 'legend')

这是它产生的结果:

最简单的解决方案是使用 sns.lineplot 而不是 sns.pointplot:

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

fig, ax = plt.subplots()
x = np.arange(10)
sns.lineplot(x=x, y=1 + np.random.rand(10).cumsum(),
             ax=ax, label='factor', color='green', marker='o')
sns.lineplot(x=x, y=2 + np.random.rand(10).cumsum(),
             ax=ax, label='conf_int+', color='red', marker='o')
sns.lineplot(x=x, y=3 + np.random.rand(10).cumsum(),
             ax=ax, label='conf_int-', color='blue', marker='o')
ax.set_title('Model M Discrete')
ax.legend(title='legend')
plt.tight_layout()
plt.show()

另一种选择是遍历生成的“pathCollections”并分配标签(由于某些原因 label=sns.pointplot 中不起作用)。

fig, ax = plt.subplots()
sns.pointplot(x=x, y=1 + np.random.rand(10).cumsum(),
              ax=ax, color='green')
sns.pointplot(x=x, y=2 + np.random.rand(10).cumsum(),
              ax=ax, color='red')
sns.pointplot(x=x, y=3 + np.random.rand(10).cumsum(),
              ax=ax, label='conf_int-', color='blue')
for curve, label in zip(ax.collections, ['factor', 'conf_int+', 'conf_int-']):
    curve.set_label(label)
ax.set_title('Model M Discrete')
ax.legend(title='legend')

另一种方法是使用自动创建图例的 hue 模拟长格式数据框:

fig, ax = plt.subplots()
x = np.arange(10)
y1 = 1 + np.random.rand(10).cumsum()
y2 = 2 + np.random.rand(10).cumsum()
y3 = 3 + np.random.rand(10).cumsum()
sns.pointplot(x=np.tile(x, 3),
              y=np.concatenate([y1, y2, y3]),
              hue=np.repeat(['factor', 'conf_int+', 'conf_int-'], len(x)),
              ax=ax, palette=['green', 'red', 'blue'])

请注意,在这两种情况下,图例中只显示一个点,而不是一条线。