猿问

Matplotlib - 如何为图例添加标签

在这里,我试图通过在 x 轴上绘制年龄和在 y 轴上绘制票价来将数据与男性因素分开,我想在图例中显示两个标签,用各自的颜色区分男性和女性。谁能帮我做这。


代码:


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


慕斯王
浏览 144回答 3
3回答

芜湖不芜

您可以使用seaborn构建在其之上的库matplotlib来执行您需要的确切任务。只需传入中的参数,即可绘制'Age'vs散点图'Fare'并对其进行颜色编码,如下所示:'Sex'huesns.scatterplotimport matplotlib.pyplot as pltimport seaborn as snsplt.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 用更少的代码和更多的功能生成更好的图。您可以seaborn使用pip install seaborn.

动漫人物

PathCollection.legend_elements方法可用于控制要创建多少图例条目以及如何标记它们。import matplotlib.pyplot as pltimport pandas as pddf = 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()

HUX布斯

这可以通过将数据隔离在两个单独的数据框中来实现,然后可以为这些数据框设置标签。import matplotlib.pyplot as pltimport pandas as pddf = 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()
随时随地看视频慕课网APP

相关分类

Python
我要回答