【问题标题】:Why is Seaborn plotting two legends, how do I remove one and fix the other?为什么 Seaborn 绘制两个图例,我如何删除一个并修复另一个?
【发布时间】:2019-12-11 02:04:14
【问题描述】:

当我运行下面显示的代码时,我得到一个包含 2 个图例的图形。我无法弄清楚为什么要绘制两个并且我无法删除其中一个。我的目标是保留图形外部的图例,删除图形内部的图例,并以某种方式停止将图例右侧切断的奇怪裁剪。

我之前有一个question 询问过类似的问题,但是通过使用 seaborns 散点图而不是 relplot 解决了这个问题。可悲的是,在该问题中有效的答案在这里都不起作用。如果这个问题是由绘制我试图制作的图形类型的“非常规”方式引起的,请告诉我。正确地做到这一点比破解解决方案要好...

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


    #setup
    sns.set(font_scale=2)
    sns.set_context('poster')

    #figure and axes
    fig = plt.figure(figsize=(20,20))
    axs = {i:fig.add_subplot(330+i) for i in range(1,10)}




    #create random data
    r = np.random.randint
    N=10
    df = pd.DataFrame(columns=['No.','x1','x2','x3','y1','y2','y3'])
    for i in range(N):
        df.loc[i] = i+1,r(50,high=100),r(50,high=100),r(50,high=100),r(50,high=100),r(50,high=100),r(50,high=100)

    #create axes labels
    x_labels = ['x1','x2','x3']
    y_labels = ['y1','y2','y3']
    xy_labels = [(x,y) for y in y_labels for x in x_labels ]


    #plot on axes
    for i,(x_label,y_label) in enumerate(xy_labels):
        if i ==0:#if statement so only one of the plots has legend='full'
            a = sns.scatterplot(
                data=df,
                x=x_label,
                y=y_label,
                legend='full', #create the legend
                ax=axs[i+1],
                hue='No.',
                palette=sns.color_palette("hls", N)
            )

            fig.legend(bbox_to_anchor=(1, 0.7), loc=2, borderaxespad=0.) #Move the legend outside the plot
            a.legend_.remove() #attempt to remove the legend
        else:
            a = sns.scatterplot(
                data=df,
                x=x_label,
                y=y_label,
                legend=False,
                ax=axs[i+1],
                hue='No.',
                palette=sns.color_palette("hls", N)
            )

        #remove axes labels from specific plots
        if i not in [0,3,6]: axs[i+1].set_ylabel('')
        if i not in [6,7,8]: axs[i+1].set_xlabel('')


    #add line plots and set limits        
    for ax in axs.values():
        sns.lineplot(x=range(50,100),y=range(50,100), ax=ax, linestyle='-')
        ax.set_xlim([50,100])
        ax.set_ylim([50,100])


    fig.tight_layout()

【问题讨论】:

  • 缺少图例错误。 #add line plots and set limits for ax in axs.values(): sns.lineplot(x=range(50,100),y=range(50,100), ax=ax, linestyle='-',legend=False)跨度>

标签: python matplotlib plot seaborn legend


【解决方案1】:

您可以在代码的最后部分添加legend=False

#setup
sns.set(font_scale=2)
sns.set_context('poster')

#figure and axes
fig = plt.figure(figsize=(20,20))
axs = {i:fig.add_subplot(330+i) for i in range(1,10)}

#create axes labels
x_labels = ['x1','x2','x3']
y_labels = ['y1','y2','y3']
xy_labels = [(x,y) for y in y_labels for x in x_labels ]

#plot on axes
for i,(x_label,y_label) in enumerate(xy_labels):
    if i ==0:#if statement so only one of the plots has legend='full'
        a = sns.scatterplot(
            data=df,
            x=x_label,
            y=y_label,
            legend='full', #create the legend
            ax=axs[i+1],
            hue='No.',
            palette=sns.color_palette("hls", N)
       )
        fig.legend(bbox_to_anchor=(1, 0.7), loc=2, borderaxespad=0.) #Move the legend outside the plot
        a.legend_.remove() #attempt to remove the legend
    else:
        a = sns.scatterplot(
            data=df,
            x=x_label,
            y=y_label,
            legend=False,
            ax=axs[i+1],
            hue='No.',
            palette=sns.color_palette("hls", N)
        )

    #remove axes labels from specific plots
    if i not in [0,3,6]: axs[i+1].set_ylabel('')
    if i not in [6,7,8]: axs[i+1].set_xlabel('')

#add line plots and set limits        
for ax in axs.values():
    sns.lineplot(x=range(50,100),y=range(50,100), ax=ax, linestyle='-', legend=False)
    ax.set_xlim([50,100])
    ax.set_ylim([50,100])

fig.tight_layout()

结果:

【讨论】:

  • 啊。哎呀。谢谢。您知道为什么要裁剪图例吗?
  • 您可以使用以下方法进行调整:fig.tight_layout(pad=0.5, w_pad=0.5, h_pad=0.5)
猜你喜欢
  • 2023-04-05
  • 1970-01-01
  • 2022-09-24
  • 2018-11-29
  • 2021-03-26
  • 2021-02-26
  • 2021-04-06
  • 1970-01-01
  • 2020-07-08
相关资源
最近更新 更多