【问题标题】:Python Seaborn Matplotlib setting line style as legendPython Seaborn Matplotlib将线条样式设置为图例
【发布时间】:2016-04-16 11:34:47
【问题描述】:

我使用 factorplot() 方法使用 seaborn 构建了以下情节。

是否可以使用线条样式作为图例来替换右侧基于线条颜色的图例?

graycolors = sns.mpl_palette('Greys_r', 4)
g = sns.factorplot(x="k", y="value", hue="class", palette=graycolors,
                   data=df, linestyles=["-", "--"])

此外,我试图在我的 factorplot 方法中使用 color="black" 参数将两条线都设为黑色,但这会导致异常“factorplot() 得到一个意外的关键字参数 'color'”。如何用相同的颜色绘制两条线并仅通过线条样式将它们分开?

【问题讨论】:

    标签: python matplotlib plot seaborn


    【解决方案1】:

    我一直在寻找一种解决方案,试图将线条样式放在 matplotlib 这样的图例中,但我还没有找到如何在 seaborn 中做到这一点。但是,为了使图例中的数据清晰,我使用了不同的markers

    import seaborn as sns
    import numpy as np
    import pandas as pd
    
    # creating some data
    n = 11
    x = np.linspace(0,2, n)
    y = np.sin(2*np.pi*x)
    y2 = np.cos(2*np.pi*x)
    data = {'x': np.append(x, x), 'y': np.append(y, y2),
            'class': np.append(np.repeat('sin', n), np.repeat('cos', n))}
    df = pd.DataFrame(data)
    
    # plot the data with the markers
    # note that I put the legend=False to move it up (otherwise it was blocking the graph)
    g=sns.factorplot(x="x", y="y", hue="class", palette=graycolors,
                     data=df, linestyles=["-", "--"], markers=['o','v'], legend=False)
    # placing the legend up
    g.axes[0][0].legend(loc=1)
    # showing graph
    plt.show()
    

    【讨论】:

      【解决方案2】:

      您可以尝试以下方法:

      h = plt.gca().get_lines()
      lg = plt.legend(handles=h, labels=['YOUR Labels List'], loc='best')
      

      对我来说效果很好。

      【讨论】:

        猜你喜欢
        • 2021-04-28
        • 1970-01-01
        • 2021-04-09
        • 1970-01-01
        • 1970-01-01
        • 2023-03-11
        • 2021-04-08
        • 2020-08-01
        • 1970-01-01
        相关资源
        最近更新 更多