Python 中 scatter 函数参数及用法详解
Python 中 scatter 函数参数及用法详解
这里有新鲜出炉的 Python 教程, 程序狗速度看过来!
Python 编程语言
Python 是一种面向对象解释型计算机程序设计语言, 由 Guido van Rossum 于 1989 年底发明, 第一个公开发行版发行于 1991 年 Python 语法简洁而清晰, 具有丰富和强大的类库它常被昵称为胶水语言, 它能够把用其他语言制作的各种模块 (尤其是 C/C++) 很轻松地联结在一起
这篇文章主要介绍了 Python 中 scatter 函数参数及用法详解, 小编觉得挺不错的, 现在分享给大家, 也给大家做个参考一起跟随小编过来看看吧
最近开始学习 Python 编程, 遇到 scatter 函数, 感觉里面的参数不知道什么意思于是查资料, 最后总结如下:
1scatter 函数原型
2 其中散点的形状参数 marker 如下:
3 其中颜色参数 c 如下:
4 基本的使用方法如下:# 导入必要的模块
importnumpyasnp
importmatplotlib.pyplotasplt
# 产生测试数据
x=np.arange(1,10)
y=x
fig=plt.figure()
ax1=fig.add_subplot(111)
# 设置标题
ax1.set_title('Scatter Plot')
# 设置 X 轴标签
plt.xlabel('X')
# 设置 Y 轴标签
plt.ylabel('Y')
# 画散点图
ax1.scatter(x,y,c='r',marker='o')
# 设置图标
plt.legend('x1')
# 显示所画的图
plt.show()
结果如下:
5 当 scatter 后面参数中数组的使用方法, 如 s, 当 s 是同 x 大小的数组, 表示 x 中的每个点对应 s 中一个大小, 其他如 c, 等用法一样, 如下:
(1)不同大小# 导入必要的模块
importnumpyasnp
importmatplotlib.pyplotasplt
# 产生测试数据
x=np.arange(1,10)
y=x
fig=plt.figure()
ax1=fig.add_subplot(111)
# 设置标题
ax1.set_title('Scatter Plot')
# 设置 X 轴标签
plt.xlabel('X')
# 设置 Y 轴标签
plt.ylabel('Y')
# 画散点图
sValue=x*10
ax1.scatter(x,y,s=sValue,c='r',marker='x')
# 设置图标
plt.legend('x1')
# 显示所画的图
plt.show()
(2)不同颜色# 导入必要的模块
importnumpyasnp
importmatplotlib.pyplotasplt
# 产生测试数据
x=np.arange(1,10)
y=x
fig=plt.figure()
ax1=fig.add_subplot(111)
# 设置标题
ax1.set_title('Scatter Plot')
# 设置 X 轴标签
plt.xlabel('X')
# 设置 Y 轴标签
plt.ylabel('Y')
# 画散点图
cValue=['r','y','g','b','r','y','g','b','r']
ax1.scatter(x,y,c=cValue,marker='s')
# 设置图标
plt.legend('x1')
# 显示所画的图
plt.show()
结果:
(3)线宽 linewidths# 导入必要的模块
importnumpyasnp
importmatplotlib.pyplotasplt
# 产生测试数据
x=np.arange(1,10)
y=x
fig=plt.figure()
ax1=fig.add_subplot(111)
# 设置标题
ax1.set_title('Scatter Plot')
# 设置 X 轴标签
plt.xlabel('X')
# 设置 Y 轴标签
plt.ylabel('Y')
# 画散点图
lValue=x
ax1.scatter(x,y,c='r',s=100,linewidths=lValue,marker='o')
# 设置图标
plt.legend('x1')
# 显示所画的图
plt.show()
注: 这就是 scatter 基本的用法
PS: 下面举个示例
本文记录了 python 中的数据可视化散点图 scatter, 令 x 作为数据(50 个点, 每个 30 维), 我们仅可视化前两维 labels 为其类别(假设有三类)
这里的 x 就用 random 来了, 具体数据具体分析
label 设定为[1:20]->1, [21:35]->2, [36:50]->3,(python 中数组连接方法: 先强制转为 list, 用 +, 再转回 array)
用 matplotlib 的 scatter 绘制散点图, legend 和 matlab 中稍有不同, 详见代码x=rand(50,30)
fromnumpyimport*
importmatplotlib
importmatplotlib.pyplotasplt
#basic
f1=plt.figure(1)
plt.subplot(211)
plt.scatter(x[:,1],x[:,0])
# with label
plt.subplot(212)
label=list(ones(20))+list(2*ones(15))+list(3*ones(15))
label=array(label)
plt.scatter(x[:,1],x[:,0],15.0*label,15.0*label)
# with legend
f2=plt.figure(2)
idx_1=find(label==1)
p1=plt.scatter(x[idx_1,1],x[idx_1,0],marker='x',color='m',label='1',s=30)
idx_2=find(label==2)
p2=plt.scatter(x[idx_2,1],x[idx_2,0],marker='+',color='c',label='2',s=50)
idx_3=find(label==3)
p3=plt.scatter(x[idx_3,1],x[idx_3,0],marker='o',color='r',label='3',s=15)
plt.legend(loc='upper right')
result:
figure(1):
figure(2):
来源: http://www.phperz.com/article/18/0213/360926.html