python画散点图带直线和图例_用Matplotlib与Seaborn画散点图并创建图例

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呈现很强的正相关。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值