3 回答
TA贡献1796条经验 获得超7个赞
您可以使用seaborn构建在其之上的库matplotlib来执行您需要的确切任务。只需传入中的参数,即可绘制'Age'vs散点图'Fare'并对其进行颜色编码,如下所示:'Sex'huesns.scatterplot
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 用更少的代码和更多的功能生成更好的图。
您可以seaborn使用pip install seaborn.
TA贡献1815条经验 获得超10个赞
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()
TA贡献1876条经验 获得超6个赞
这可以通过将数据隔离在两个单独的数据框中来实现,然后可以为这些数据框设置标签。
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()
添加回答
举报