【问题标题】:Legend not showing when plotting multiple seaborn plots绘制多个 seaborn 地块时未显示图例
【发布时间】:2018-02-12 10:08:57
【问题描述】:

我通常对 matplotlib 图例没有问题,但这是我第一次将它用于多个 seaborn 地块,以下不起作用。

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

我做错了什么?

【问题讨论】:

    标签: matplotlib seaborn


    【解决方案1】:

    seaborn.regplot 返回一个坐标区。您不能从坐标区创建图例代理句柄。然而,这甚至没有必要。从图例中删除handles,它应该会给出所需的情节。

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

    【讨论】:

    • 对我不起作用:它给出“TypeError: legend() missing 1 required positional argument: 'handles'”。我正在使用 matplotlib v2.0.2
    • 是的,fig.legend() 只能从 2.1 开始。但是您可以调用坐标轴上的图例,因为所有图都是该坐标轴的一部分,ax.legend()
    猜你喜欢
    • 1970-01-01
    • 2020-04-25
    • 2021-11-03
    • 2021-12-24
    • 2021-05-07
    • 2020-10-22
    • 1970-01-01
    • 2017-11-19
    • 2020-06-02
    相关资源
    最近更新 更多