python画散点图|scatter()函数小试牛刀(入门级教程)

在前述学习过程中,已经初步接触了scatter()模块,知道其专门可以输出散点图。

本次探索一下scatter()模块的一些简单用法,供大家参考。前述学习记录请见链接:

python动画教程|Animations using Matplotlib-官网教程程序解读-CSDN博客

【1】matplotlib官网scatter()教程

打开matplotlib官网,搜索scatter,页面结果显示如下:

Search — Matplotlib 3.9.2 documentation

大概有182个结果,实际上我们常常直接使用的代码位于最上面,也就是前两个:

0630a4a0d6864bf6bce4caa39aa4e9f9.png图1

由图1可见:matplotlib中,axes和pyplot两个模块均可以调用scatter绘制散点图。

为测试axes和pyplot两个模块调用scatter绘制散点图,需要自己编写程序。

按照熟悉的步骤,我们首先引入必须的模块:

import numpy as np #引入numpy
import matplotlib.pyplot as plt #引入matplotlib
import matplotlib.animation as ani
#fig,ax=plt.subplots()
t=np.linspace(0,2*np.pi,50) #定义自变量t,t在(0,2pi)区间内,取50个数值,包括0,单不包括2pi
s=np.sin(t) #定义正弦函数

【2】plt调用scatter()绘制散点图 

在必须模块后,增加下述代码:

scat=plt.scatter(t,s,label='scatter') #输出散点图
plt.plot(t,s,'y',label='line') #输出连续线图
plt.legend() #输出图例
plt.show() #输出图形

运行后的输出结果为:

fbfb8f3df7284ac6ba92576c74b025dd.png

图2

由图2可见,plt/pyplot模块调用scatter()子模块成功输出散点图。

【3】axes调用scatter()绘制散点图

在必须模块后,增加下述代码:

fig,ax=plt.subplots() #定义ax类变量
scat=ax.scatter(t,s,label='axes_scatter') #输出散点图
plt.plot(t,s,'y',label='line') #输出连续线图
plt.legend() #输出图例
plt.show() #输出图形

运行后的输出结果为:

2a426ffa9ac34647822fae7948336d48.png

图3

由图3可见,plt/pyplot模块调用scatter()子模块成功输出散点图。

【4】pyplot和axes调用scatter()绘制散点图对比

输入以下代码:

import numpy as np #引入numpy
import matplotlib.pyplot as plt #引入matplotlib
import matplotlib.animation as ani
#fig,ax=plt.subplots()
t=np.linspace(0,2*np.pi,50) #定义自变量t,t在(0,2pi)区间内,取50个数值,包括0,单不包括2pi
s=np.sin(t) #定义正弦函数
fig,ax=plt.subplots() #定义ax类变量
ax_scat=ax.scatter(t,s,label='axes_scatter',linewidths=6) #输出散点图
plt_scat=plt.scatter(t,s,label='pyplot_scatter') #输出散点图
plt.plot(t,s,'y',label='line') #输出连续线图
plt.legend() #输出图例
plt.show() #输出图形

运行后的输出结果为:

446aad4d67e7469684a8690424530756.png

图4

由图4可见,plt/pyplot和ax/axes模块调用scatter()子模块均成功输出散点图,二者输出结果到目前没有区别。

【5】总结

本文初步研究了python用scatter()函数画散点图,在matplotlib模块上,通过plt/pyplot和ax/axes模块调用scatter()子模块均成功输出散点图,两种散点图没有区别。

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值