使用matplotlib中scatter()绘制散点图

1、二维散点图

二维散点图的函数原型:

matplotlib.pyplot.scatter(x, y, s=None, c=None, marker=None, cmap=None, norm=None,
                          vmin=None, vmax=None, alpha=None, linewidths=None,
                          verts=None, edgecolors=None, hold=None, data=None,
                          **kwargs)
  • x, y对应了平面点的位置,
  • s控制点大小,
  • c对应颜色指示值,也就是如果采用了渐变色的话,我们设置c=x就能使得点的颜色根据点的x值变化,
  • cmap调整渐变色或者颜色列表的种类
  • marker控制点的形状
  • alpha控制点的透明度,我喜欢在数据量大的时候设置较小的alpha值,然后调整一下s值,这样产生重叠效果使得数据的聚集特征会很好地显示出来:看一下效果

第一个设置不透明

fig = plt.figure()

x = np.random.randn(10000)
y = np.random.randn(10000)
plt.scatter(x, y, c='b')
plt.scatter(x+4, y, c='r')

 第二个设置透明

fig = plt.figure()

x = np.random.randn(10000)
y = np.random.randn(10000)
plt.scatter(x, y, c='b', alpha=0.05)
plt.scatter(x+4, y, c='r', alpha=0.05)

 然后调整下点的大小

fig = plt.figure()

x = np.random.randn(10000)
y = np.random.randn(10000)
plt.scatter(x, y, c='b', alpha=0.05, s=10)
plt.scatter(x+4, y, c='r', alpha=0.05, s=10)

2、三维散点图

三维散点图函数原型:

p3d.Axes3D.scatter( xs, ys, zs=0, zdir=’z’, s=20, c=None, depthshade=True, 
                   *args, **kwargs )

p3d.Axes3D.scatter3D( xs, ys, zs=0, zdir=’z’, s=20, c=None, depthshade=True,
                   *args, **kwargs)

三维散点图在p3d.Axes3D中有两个版本,但效果一样:

  • xs, ys代表点的x, y轴坐标
  • zs代表z轴坐标,但有两种形式,第一种就是取一个标量,函数原型里默认就是一个标量0,也就是默认所有的点都画在一个z=0的水平平面上;第二种就是取和xsys同样shape的数组,从而指定每个点的实际z轴坐标,如下:

zs默认为0;

fig = plt.figure()
ax = Axes3D(fig)

x = np.random.randn(10000)
y = np.random.randn(10000)
ax.scatter(x, y, c='b', s=10, alpha=0.05)
ax.scatter(x+4, y, c='r', s=10, alpha=0.05)

 zs取一个标量

fig = plt.figure()
ax = Axes3D(fig)

x = np.random.randn(10000)
y = np.random.randn(10000)
ax.scatter(x, y, c='b', s=10, alpha=0.05)
ax.scatter(x+4, y, 2, c='r', s=10, alpha=0.05)

 zs取一个数组

fig = plt.figure()
ax = Axes3D(fig)

z = 6*np.random.randn(5000)
x = np.sin(z)
y = np.cos(z)
ax.scatter(x, y, z, c='r', s=10, alpha=0.05)

 参考:https://www.jianshu.com/p/9390b49ad993

猜你喜欢

转载自www.cnblogs.com/mliu222/p/11920380.html