【问题标题】:Matplotlib - How can I add labels to legendMatplotlib - 如何向图例添加标签
【发布时间】:2020-12-13 18:04:34
【问题描述】:

在这里,我试图通过在 x 轴上绘制 Age 并在 y 轴上绘制 Fare 来将数据与因素分开,我想在图例中显示两个标签,用各自的颜色区分男性和女性。任何人都可以帮我做这件事。

代码:

import matplotlib.pyplot as plt
import pandas as pd
df = pd.read_csv('https://sololearn.com/uploads/files/titanic.csv')
df['male']=df['Sex']=='male'
sc1= plt.scatter(df['Age'],df['Fare'],c=df['male'])
plt.legend()
plt.show()

【问题讨论】:

    标签: python pandas matplotlib legend


    【解决方案1】:

    您可以使用构建在matplotlib 之上的seaborn 库来执行您需要的确切任务。您可以通过在hue 中传递hue 参数来散点图'Age''Fare' 并通过'Sex' 对其进行颜色编码,如下所示:

    import matplotlib.pyplot as plt
    import seaborn as sns
    
    plt.figure()
    
    # No need to call plt.legend, seaborn will generate the labels and legend
    # automatically.
    sns.scatterplot(df['Age'], df['Fare'], hue=df['Sex'])
    
    plt.show()
    

    Seaborn 以更少的代码和更多的功能生成更好的绘图。

    您可以使用 pip install seaborn 从 PyPI 安装 seaborn

    参考:Seaborn docs

    【讨论】:

      【解决方案2】:

      PathCollection.legend_elements 方法 可用于控制要创建多少图例条目以及它们如何 应该贴上标签。

      import matplotlib.pyplot as plt
      import pandas as pd
      
      df = pd.read_csv('https://sololearn.com/uploads/files/titanic.csv')
      df['male'] = df['Sex']=='male'
      
      sc1= plt.scatter(df['Age'], df['Fare'], c=df['male'])
      
      plt.legend(handles=sc1.legend_elements()[0], labels=['male', 'female'])
      
      plt.show()
      

      Legend guideScatter plots with a legend 供参考。

      【讨论】:

        【解决方案3】:

        这可以通过将数据分离到两个单独的数据帧中来实现,然后可以为这些数据帧设置标签。

        import matplotlib.pyplot as plt
        import pandas as pd
        df = pd.read_csv('https://sololearn.com/uploads/files/titanic.csv')
        subset1 = df[(df['Sex'] == 'male')]
        subset2 = df[(df['Sex'] != 'male')]
        plt.scatter(subset1['Age'], subset1['Fare'], label = 'Male')
        plt.scatter(subset2['Age'], subset2['Fare'], label = 'Female')
        plt.legend()
        plt.show()
        

        enter image description here

        【讨论】:

          猜你喜欢
          • 2014-06-22
          • 2018-05-18
          • 2020-11-30
          • 1970-01-01
          • 2022-01-11
          • 2014-10-18
          • 2020-08-18
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多