一、用plt.plot()画散点图
import matplotlib
.pyplot
as plt
import numpy
as np
plt
.style
.use
('seaborn-whitegrid')
x
= np
.linspace
(0, 10, 30)
y
= np
.sin
(x
)
plt
.plot
(x
, y
, 'o', color
='black')
函数的第三个参数是一个字符,表示图形符号的类型。和之前使用的"-“和”–"设置线条属性类似。对应的还有下面演示的:
rng
= np
.random
.RandomState
(0)
for marker
in ['o', '.', ',', 'x', '+', 'v', '^', '<', '>', 's', 'd']:
plt
.plot
(rng
.rand
(5), rng
.rand
(5), marker
,
label
="marker='{0}'".format(marker
))
plt
.legend
(numpoints
=1)
plt
.xlim
(0, 1.8)
1、用线条链接散点
plt
.plot
(x
, y
, '-ok')
2、自定义线条和散点属性:
plt
.plot
(x
, y
, '-p', color
='gray',
markersize
=15, linewidth
=4,
markerfacecolor
='white',
markeredgecolor
='gray',
markeredgewidth
=2)
plt
.ylim
(-1.2, 1.2)
二、用plt.scatter()画散点图
https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.scatter.html#matplotlib.pyplot.scatter plt.scatter与plt.plot的不同之处在于:前者在创建散点图时具有更高的灵活性,可以单独控制每个散点与数据匹配,也可以让每个散点具有不同的属性。
plt
.scatter
(x
, y
, marker
='o')
1、改变散点的大小、颜色与透明度
rng
= np
.random
.RandomState
(0)
x
= rng
.randn
(100)
y
= rng
.randn
(100)
colors
= rng
.rand
(100)
sizes
= 1000 * rng
.rand
(100)
plt
.scatter
(x
, y
, c
=colors
, s
=sizes
, alpha
=0.3, cmap
='viridis')
plt
.colorbar
()
2、用散点属性对鸢尾花的特征进行编码:
from sklearn
.datasets
import load_iris
iris
= load_iris
()
features
= iris
.data
.T
plt
.scatter
(features
[0], features
[1], alpha
=0.2,
s
=100*features
[3], c
=iris
.target
, cmap
='viridis')
plt
.xlabel
(iris
.feature_names
[0])
plt
.ylabel
(iris
.feature_names
[1])
plot与scatter的效率对比
在数据量比较小的时候,两者在效率上的差异不大。但是,当数据量变大时,plt.plot的效率将大大高于plt.scatter的效率。这是因为plt.scatter会对每一个散点进行单独的大小和颜色的渲染,渲染器会消耗更多的资源。