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()
添加回答
舉報