怎么用Python绘制散点图
发表于:2025-11-08 作者:千家信息网编辑
千家信息网最后更新 2025年11月08日,这篇文章主要讲解了"怎么用Python绘制散点图",文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习"怎么用Python绘制散点图"吧!少废话,直接上代码im
千家信息网最后更新 2025年11月08日怎么用Python绘制散点图
这篇文章主要讲解了"怎么用Python绘制散点图",文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习"怎么用Python绘制散点图"吧!
少废话,直接上代码
import matplotlib.pyplot as pltimport numpy as np# 1. 首先是导入包,创建数据n = 10x = np.random.rand(n) * 2# 随机产生10个0~2之间的x坐标y = np.random.rand(n) * 2# 随机产生10个0~2之间的y坐标# 2.创建一张figurefig = plt.figure(1)# 3. 设置颜色 color 值【可选参数,即可填可不填】,方式有几种# colors = np.random.rand(n) # 随机产生10个0~1之间的颜色值,或者colors = ['r', 'g', 'y', 'b', 'r', 'c', 'g', 'b', 'k', 'm'] # 可设置随机数取# 4. 设置点的面积大小 area 值 【可选参数】area = 20*np.arange(1, n+1)# 5. 设置点的边界线宽度 【可选参数】widths = np.arange(n)# 0-9的数字# 6. 正式绘制散点图:scatterplt.scatter(x, y, s=area, c=colors, linewidths=widths, alpha=0.5, marker='o')# 7. 设置轴标签:xlabel、ylabel#设置X轴标签plt.xlabel('X坐标')#设置Y轴标签plt.ylabel('Y坐标')# 8. 设置图标题:titleplt.title('test绘图函数')# 9. 设置轴的上下限显示值:xlim、ylim# 设置横轴的上下限值plt.xlim(-0.5, 2.5)# 设置纵轴的上下限值plt.ylim(-0.5, 2.5)# 10. 设置轴的刻度值:xticks、yticks# 设置横轴精准刻度plt.xticks(np.arange(np.min(x)-0.2, np.max(x)+0.2, step=0.3))# 设置纵轴精准刻度plt.yticks(np.arange(np.min(y)-0.2, np.max(y)+0.2, step=0.3))# 也可按照xlim和ylim来设置# 设置横轴精准刻度plt.xticks(np.arange(-0.5, 2.5, step=0.5))# 设置纵轴精准刻度plt.yticks(np.arange(-0.5, 2.5, step=0.5)) # 11. 在图中某些点上(位置)显示标签:annotate# plt.annotate("(" + str(round(x[2], 2)) + ", " + str(round(y[2], 2)) + ")", xy=(x[2], y[2]), fontsize=10, xycoords='data')# 或者plt.annotate("({0},{1})".format(round(x[2],2), round(y[2],2)), xy=(x[2], y[2]), fontsize=10, xycoords='data')# xycoords='data' 以data值为基准# 设置字体大小为 10# 12. 在图中某些位置显示文本:textplt.text(round(x[6],2), round(y[6],2), "good point", fontdict={'size': 10, 'color': 'red'}) # fontdict设置文本字体# Add text to the axes.# 13. 设置显示中文plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签plt.rcParams['axes.unicode_minus']=False #用来正常显示负号# 14. 设置legend,【注意,'绘图测试':一定要是可迭代格式,例如元组或者列表,要不然只会显示第一个字符,也就是legend会显示不全】plt.legend(['绘图测试'], loc=2, fontsize=10)# plt.legend(['绘图测试'], loc='upper left', markerscale = 0.5, fontsize = 10) #这个也可# markerscale:The relative size of legend markers compared with the originally drawn ones.# 15. 保存图片 savefigplt.savefig('test_xx.png', dpi=200, bbox_inches='tight', transparent=False)# dpi: The resolution in dots per inch,设置分辨率,用于改变清晰度# If *True*, the axes patches will all be transparent# 16. 显示图片 showplt.show()scatter主要参数:
def scatter(self, x, y, s=None, c=None, marker=None, cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, verts=None, edgecolors=None, **kwargs): """ A scatter plot of *y* vs *x* with varying marker size and/or color. Parameters ---------- x, y : array_like, shape (n, ) The data positions. s : scalar or array_like, shape (n, ), optional The marker size in points**2. Default is ``rcParams['lines.markersize'] ** 2``. c : color, sequence, or sequence of color, optional, default: 'b' The marker color. Possible values: - A single color format string. - A sequence of color specifications of length n. - A sequence of n numbers to be mapped to colors using *cmap* and *norm*. - A 2-D array in which the rows are RGB or RGBA. Note that *c* should not be a single numeric RGB or RGBA sequence because that is indistinguishable from an array of values to be colormapped. If you want to specify the same RGB or RGBA value for all points, use a 2-D array with a single row. marker : `~matplotlib.markers.MarkerStyle`, optional, default: 'o' The marker style. *marker* can be either an instance of the class or the text shorthand for a particular marker. See `~matplotlib.markers` for more information marker styles. cmap : `~matplotlib.colors.Colormap`, optional, default: None A `.Colormap` instance or registered colormap name. *cmap* is only used if *c* is an array of floats. If ``None``, defaults to rc ``image.cmap``. alpha : scalar, optional, default: None The alpha blending value, between 0 (transparent) and 1 (opaque). linewidths : scalar or array_like, optional, default: None The linewidth of the marker edges. Note: The default *edgecolors* is 'face'. You may want to change this as well. If *None*, defaults to rcParams ``lines.linewidth``.
设置legend,【注意,'绘图测试’:一定要是可迭代格式,例如元组或者列表,要不然只会显示第一个字符,也就是legend会显示不全】
plt.legend(['绘图测试'], loc=2, fontsize = 10)# plt.legend(['绘图测试'], loc='upper left', markerscale = 0.5, fontsize = 10) #这个也可# markerscale:The relative size of legend markers compared with the originally drawn ones.
其参数loc对应为:

运行结果:

补充
除了二维的散点图,Python还能绘制三维的散点图,下面的示例代码
import matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3Dimport numpy as np # 随机种子np.random.seed(1) def randrange(n, vmin, vmax): ''' 使数据分布均匀(vmin, vmax). ''' return (vmax - vmin)*np.random.rand(n) + vmin fig = plt.figure()ax = fig.add_subplot(111, projection='3d') # 可进行多图绘制 n = 500 # 对于每一组样式和范围设置,在由x在[23,32]、y在[0,100]、# z在[zlow,zhigh]中定义的框中绘制n个随机点for m, zlow, zhigh in [('o', -50, -25), ('^', -30, -5)]: xs = randrange(n, 23, 32) ys = randrange(n, 0, 100) zs = randrange(n, zlow, zhigh) ax.scatter(xs, ys, zs, marker=m) # 绘图 # X、Y、Z的标签ax.set_xlabel('X Label')ax.set_ylabel('Y Label')ax.set_zlabel('Z Label') plt.show()输出结果:
感谢各位的阅读,以上就是"怎么用Python绘制散点图"的内容了,经过本文的学习后,相信大家对怎么用Python绘制散点图这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是,小编将为大家推送更多相关知识点的文章,欢迎关注!
绘图
标签
测试
刻度
参数
精准
坐标
上下
之间
纵轴
横轴
学习
也就是
代码
位置
内容
图片
大小
字体
字符
数据库的安全要保护哪些东西
数据库安全各自的含义是什么
生产安全数据库录入
数据库的安全性及管理
数据库安全策略包含哪些
海淀数据库安全审计系统
建立农村房屋安全信息数据库
易用的数据库客户端支持安全管理
连接数据库失败ssl安全错误
数据库的锁怎样保障安全
udp服务器的设计
招商银行网络技术公司
数据库的图片是什么
sql 数据库关系是什么
像素工厂服务器导入地图
关于网络安全心得体会
服务器访问量过大怎么扩容
富士胶片中国软件开发中心
聚焦网络技术公司
西安智乐互娱网络技术有限公司
e4a数据库查询指定字段
深圳德诚互联网科技有限公司
数据库和微服务
软件开发时期有几个阶段
中方是网络安全的坚定维护者
烟台宏聚网络技术
女生网络安全与执法
税务局数据库维护
网络安全行业专家名单
信息新技术报告网络安全图片
计算机网络安全国内外现状
河南调度服务器安装云服务器
mysql数据库怎么找工作
网络安全加速器下载
网络安全线上知识问答题
yw服务器是什么意思
数据库系统由五
软件开发团队系统分析师作用
青岛调度服务器品牌
柳州租车软件开发