Matplotlib与Seaborn是在python中很常用的两个画图库。
安装两个库
pip install matplotlib
pip install seaborn1
2
用Matplotlib画散点图
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd1
2
3
4
从seaborn上面加载文档
iris = sns.load_dataset("iris")
print(iris.head())
sepal_length sepal_width petal_length petal_width species
0 5.1 3.5 1.4 0.2 setosa
1 4.9 3.0 1.4 0.2 setosa
2 4.7 3.2 1.3 0.2 setosa
3 4.6 3.1 1.5 0.2 setosa
4 5.0 3.6 1.4 0.2 setosa1
2
3
4
5
6
7
8
生成颜色字典
species_group = iris.groupby("species")
color_used = ["red", "green", "blue"]
colors = dict(zip(species_group.count().index, color_used))1
2
3
设置画布的格式
fig, ax = plt.subplots(figsize=(10, 8))
ax.set_title("Scatter")
ax.set_xlabel("sepal_length")
ax.set_ylabel("petal_length")1
2
3
4
开始画图
for species, group in species_group:
plt.scatter(group["sepal_length"]
, group["petal_length"]
, label=species # 生成图例名字
, c=colors[species] # 根据“species”设置对应的散点与图例颜色
, alpha=0.5)
plt.legend(title="Species", fancybox=True, loc=2)
plt.show()1
2
3
4
5
6
7
8
用Seaborn画散点图
iris = sns.load_dataset("iris")
sns.pairplot(iris,hue="species",x_vars="sepal_length",y_vars="petal_length",height=8)
plt.show()1
2
3
sepal_length与petal_length呈现很强的正相关。