使用matplotlib中scatter方法画散点图


Posted in Python onMarch 19, 2019

本文实例为大家分享了用matplotlib中scatter方法画散点图的具体代码,供大家参考,具体内容如下

1、最简单的绘制方式

绘制散点图是数据分析过程中的常见需求。python中最有名的画图工具是matplotlib,matplotlib中的scatter方法可以方便实现画散点图的需求。下面我们来绘制一个最简单的散点图。

数据格式如下:

0   746403
1   1263043
2   982360
3   1202602
...

其中第一列为X坐标,第二列为Y坐标。下面我们来画图。

#!/usr/bin/env python
#coding:utf-8

import matplotlib.pyplot as plt 

def pltpicture():
 file = "xxx"                                      
 xlist = []
 ylist = []
 with open(file, "r") as f:
  for line in f.readlines():
   lines = line.strip().split()
   if len(lines) != 2 or int(lines[1]) < 100000:
    continue
   x, y = int(lines[0]), int(lines[1])
   xlist.append(x)
   ylist.append(y)

 plt.xlabel('X')
 plt.ylabel('Y')
 plt.scatter(xlist, ylist)
 plt.show()

使用matplotlib中scatter方法画散点图

2、更漂亮一些的画图方式

上面的图片比较粗糙,是最简单的方式,没有任何相关的配置项。下面我们再用另外一份数据集画出更漂亮一点的图。
数据集来自网络的公开数据集,数据格式如下:

40920   8.326976    0.953952    3
14488   7.153469    1.673904    2
26052   1.441871    0.805124    1
75136   13.147394   0.428964    1
...

第一列每年获得的飞行常客里程数;
第二列玩视频游戏所耗时间百分比;
第三列每周消费的冰淇淋公升数;
第四列为label:
1表示不喜欢的人
2表示魅力一般的人
3表示极具魅力的人

现在将每年获取的飞行里程数作为X坐标,玩视频游戏所消耗的事件百分比作为Y坐标,画出图。

from matplotlib import pyplot as plt

file = "/home/mi/wanglei/data/datingTestSet2.txt"
label1X, label1Y, label2X, label2Y, label3X, label3Y = [], [], [], [], [], []

with open(file, "r") as f:
 for line in f:
  lines = line.strip().split()
  if len(lines) != 4:
   continue
  distance, rate, label = lines[0], lines[1], lines[3]
  if label == "1":
   label1X.append(distance)
   label1Y.append(rate)

  elif label == "2":
   label2X.append(distance)
   label2Y.append(rate)

  elif label == "3":
   label3X.append(distance)
   label3Y.append(rate)

plt.figure(figsize=(8, 5), dpi=80)
axes = plt.subplot(111)

label1 = axes.scatter(label1X, label1Y, s=20, c="red")
label2 = axes.scatter(label2X, label2Y, s=40, c="green")
label3 = axes.scatter(label3X, label3Y, s=50, c="blue")

plt.xlabel("every year fly distance")
plt.ylabel("play video game rate")
axes.legend((label1, label2, label3), ("don't like", "attraction common", "attraction perfect"), loc=2)

plt.show()

最后效果图:

使用matplotlib中scatter方法画散点图

3、scatter函数详解

我们来看看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):
  """
  Make a scatter plot of `x` vs `y`

  Marker size is scaled by `s` and marker color is mapped to `c`

  Parameters
  ----------
  x, y : array_like, shape (n, )
   Input data

  s : scalar or array_like, shape (n, ), optional
   size in points^2. Default is `rcParams['lines.markersize'] ** 2`.

  c : color, sequence, or sequence of color, optional, default: 'b'
   `c` can be a single color format string, or a sequence of color
   specifications of length `N`, or a sequence of `N` numbers to be
   mapped to colors using the `cmap` and `norm` specified via kwargs
   (see below). 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. `c` can be a 2-D array in which the
   rows are RGB or RGBA, however, including the case of a single
   row to specify the same color for all points.

  marker : `~matplotlib.markers.MarkerStyle`, optional, default: 'o'
   See `~matplotlib.markers` for more information on the different
   styles of markers scatter supports. `marker` can be either
   an instance of the class or the text shorthand for a particular
   marker.

  cmap : `~matplotlib.colors.Colormap`, optional, default: None
   A `~matplotlib.colors.Colormap` instance or registered name.
   `cmap` is only used if `c` is an array of floats. If None,
   defaults to rc `image.cmap`.

  norm : `~matplotlib.colors.Normalize`, optional, default: None
   A `~matplotlib.colors.Normalize` instance is used to scale
   luminance data to 0, 1. `norm` is only used if `c` is an array of
   floats. If `None`, use the default :func:`normalize`.

  vmin, vmax : scalar, optional, default: None
   `vmin` and `vmax` are used in conjunction with `norm` to normalize
   luminance data. If either are `None`, the min and max of the
   color array is used. Note if you pass a `norm` instance, your
   settings for `vmin` and `vmax` will be ignored.

  alpha : scalar, optional, default: None
   The alpha blending value, between 0 (transparent) and 1 (opaque)

  linewidths : scalar or array_like, optional, default: None
   If None, defaults to (lines.linewidth,).

  verts : sequence of (x, y), optional
   If `marker` is None, these vertices will be used to
   construct the marker. The center of the marker is located
   at (0,0) in normalized units. The overall marker is rescaled
   by ``s``.

  edgecolors : color or sequence of color, optional, default: None
   If None, defaults to 'face'

   If 'face', the edge color will always be the same as
   the face color.

   If it is 'none', the patch boundary will not
   be drawn.

   For non-filled markers, the `edgecolors` kwarg
   is ignored and forced to 'face' internally.

  Returns
  -------
  paths : `~matplotlib.collections.PathCollection`

  Other parameters
  ----------------
  kwargs : `~matplotlib.collections.Collection` properties

  See Also
  --------
  plot : to plot scatter plots when markers are identical in size and
   color

  Notes
  -----

  * The `plot` function will be faster for scatterplots where markers
   don't vary in size or color.

  * Any or all of `x`, `y`, `s`, and `c` may be masked arrays, in which
   case all masks will be combined and only unmasked points will be
   plotted.

   Fundamentally, scatter works with 1-D arrays; `x`, `y`, `s`, and `c`
   may be input as 2-D arrays, but within scatter they will be
   flattened. The exception is `c`, which will be flattened only if its
   size matches the size of `x` and `y`.

  Examples
  --------
  .. plot:: mpl_examples/shapes_and_collections/scatter_demo.py

  """

其中具体的参数含义如下:

x,y是相同长度的数组。
s可以是标量,或者与x,y长度相同的数组,表明散点的大小。默认为20。
c即color,表示点的颜色。
marker 是散点的形状。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python实现单词翻译功能
Jun 06 Python
使用Python AIML搭建聊天机器人的方法示例
Jul 09 Python
python安装twisted的问题解析
Aug 21 Python
python re正则匹配网页中图片url地址的方法
Dec 20 Python
pyqt5 QProgressBar清空进度条的实例
Jun 21 Python
使用Python轻松完成垃圾分类(基于图像识别)
Jul 09 Python
python中bs4.BeautifulSoup的基本用法
Jul 27 Python
python中时间转换datetime和pd.to_datetime详析
Aug 11 Python
Python中生成一个指定长度的随机字符串实现示例
Nov 06 Python
PyQt QMainWindow的使用示例
Mar 24 Python
Python实现Hash算法
Mar 18 Python
Python实现数据的序列化操作详解
Jul 07 Python
详解django+django-celery+celery的整合实战
Mar 19 #Python
详解Python正则表达式re模块
Mar 19 #Python
python matplotlib画图库学习绘制常用的图
Mar 19 #Python
详解python的四种内置数据结构
Mar 19 #Python
python3使用matplotlib绘制条形图
Mar 25 #Python
python3使用matplotlib绘制散点图
Mar 19 #Python
浅谈PYTHON 关于文件的操作
Mar 19 #Python
You might like
php接口与接口引用的深入解析
2013/08/09 PHP
PHP生成网站桌面快捷方式代码分享
2014/10/11 PHP
PHP实现微信商户支付企业付款到零钱功能
2018/09/30 PHP
用js实现多域名不同文件的调用方法
2007/01/12 Javascript
奇妙的js
2007/09/24 Javascript
Js 弹出框口并返回值的两种常用方法
2010/12/30 Javascript
使用jquery插件实现图片延迟加载技术详细说明
2011/03/12 Javascript
JQueryEasyUI Layout布局框架的使用
2013/04/08 Javascript
给html超链接设置事件不使用href来完成跳
2014/04/20 Javascript
javascript基于DOM实现权限选择实例分析
2015/05/14 Javascript
JavaScript中的boolean布尔值使用学习及相关技巧讲解
2016/05/26 Javascript
微信小程序Server端环境配置详解(SSL, Nginx HTTPS,TLS 1.2 升级)
2017/01/12 Javascript
jquery实现tab选项卡切换效果(悬停、下方横线动画位移)
2017/05/05 jQuery
vue中计算属性(computed)、methods和watched之间的区别
2017/07/27 Javascript
详解EasyUi控件中的Datagrid
2017/08/23 Javascript
jQueryMobile之窗体长内容的缺陷与解决方法实例分析
2017/09/20 jQuery
vue实现的上传图片到数据库并显示到页面功能示例
2018/03/17 Javascript
详解vue组件基础
2018/05/04 Javascript
Vue2 监听属性改变watch的实例代码
2018/08/27 Javascript
JavaScript鼠标拖拽事件详解
2020/04/03 Javascript
JavaScript实现图片合成下载的示例
2020/11/19 Javascript
详解Python命令行解析工具Argparse
2016/04/20 Python
python设计模式大全
2016/06/27 Python
python利用urllib和urllib2访问http的GET/POST详解
2017/09/27 Python
python利用opencv实现SIFT特征提取与匹配
2020/03/05 Python
python boto和boto3操作bucket的示例
2020/10/30 Python
Restful_framework视图组件代码实例解析
2020/11/17 Python
Python  Asyncio模块实现的生产消费者模型的方法
2021/03/01 Python
eDreams澳大利亚:预订机票、酒店和度假产品
2017/04/19 全球购物
德国机场停车位比较和预订网站:Ich-parke-billiger
2018/01/08 全球购物
通信工程毕业生求职信
2013/11/16 职场文书
工商管理实习生自我鉴定范文
2013/12/18 职场文书
3.12植树节活动总结2014
2014/03/13 职场文书
买卖合同协议书范本
2014/10/18 职场文书
借款民事起诉状范文
2015/05/19 职场文书
银行中层干部培训心得体会
2016/01/11 职场文书