Legend not showing when plotting multiple seaborn plots

天大地大妈咪最大 提交于 2021-01-28 01:05:54

问题


I typically don't have problems with matplotlib legend, but this is the first time I am using it with multiple seaborn plots, and the following does not work.

fig = plt.figure(figsize=(10,6))
a =sns.regplot(x='VarX', y='VarY1', data=data)
b = sns.regplot(x='VarX', y='VarY2', data=data)
c = sns.regplot(x='VarX', y='VarY3', data=data)
fig.legend(handles=[a, b, c],labels=['First','Second','Third'])
fig.show()

What am I doing wrong?


回答1:


seaborn.regplot returns an axes. You cannot create a legend proxy handle from an axes. However this is not even necessary. Remove the handles from the legend and it should give the desired plot.

import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)
import pandas as pd
import seaborn as sns

data=pd.DataFrame({"VarX" : np.arange(10), 
                   'VarY1': np.random.rand(10),
                   'VarY2': np.random.rand(10),
                   'VarY3': np.random.rand(10)})

fig = plt.figure(figsize=(10,6))
sns.regplot(x='VarX', y='VarY1', data=data)
sns.regplot(x='VarX', y='VarY2', data=data)
sns.regplot(x='VarX', y='VarY3', data=data)
fig.legend(labels=['First','Second','Third'])
plt.show()



来源:https://stackoverflow.com/questions/48743867/legend-not-showing-when-plotting-multiple-seaborn-plots

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!