如果我用python的pyplot画散点图,怎么可以让不同的类别显示不同的颜色,效果大致如下(网图)
谢谢!
2个回答
可以用seaborn和matplotlib一起
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
N = 100
genders= ['Female', 'Male']
df = pd.DataFrame({
'Height': np.random.uniform(low=130, high=200, size=N),
'Weight': np.random.uniform(low=40, high=100, size=N),
'Gender': np.random.choice(genders, size=N)
})
fg = sns.FacetGrid(data=df, hue='Gender', hue_order=genders)
fg.map(plt.scatter, 'Weight', 'Height').add_legend()
plt.show()
import matplotlib.pyplot as plt
plt.style.use('ggplot')
import pandas as pd
import numpy as np
#随机生成两个dataframe
d1 = pd.DataFrame(columns=['x', 'y'])
d1['x'] = np.random.normal(0, 1, 100)
d1['y'] = np.random.normal(0, 1, 100)
d2 = pd.DataFrame(columns=['x', 'y'])
d2['x'] = np.random.normal(2, 1, 100)
d2['y'] = np.random.normal(2, 1, 100)
#分别画出scatter图,但是设置不同的颜色
plt.scatter(d1['x'], d1['y'], color='blue', label='d1 points')
plt.scatter(d2['x'], d2['y'], color='green', label='d2 points')
#设置图例
plt.legend(loc=(1, 0))
#显示图片
plt.show()