使用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中Continue语句的用法的举例详解
May 14 Python
Python文档生成工具pydoc使用介绍
Jun 02 Python
Python按行读取文件的简单实现方法
Jun 22 Python
python多线程调用exit无法退出的解决方法
Feb 18 Python
Django框架验证码用法实例分析
May 10 Python
Django框架文件上传与自定义图片上传路径、上传文件名操作分析
May 10 Python
pyqt 实现在Widgets中显示图片和文字的方法
Jun 13 Python
实例讲解Python 迭代器与生成器
Jul 08 Python
深入分析python 排序
Aug 24 Python
Django修改app名称和数据表迁移方案实现
Sep 17 Python
爬虫代理的cookie如何生成运行
Sep 22 Python
python3.7中安装paddleocr及paddlepaddle包的多种方法
Nov 27 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
PHP5.0正式发布 不完全兼容PHP4 新增多项功能
2006/10/09 PHP
PHP调用Twitter的RSS的实现代码
2010/03/10 PHP
PHP explode()函数的几个应用和implode()函数有什么区别
2015/11/05 PHP
php获取当前月与上个月月初及月末时间戳的方法
2016/12/05 PHP
PHP设计模式之数据访问对象模式(DAO)原理与用法实例分析
2019/12/12 PHP
javascript 广告后加载,加载完页面再加载广告
2010/11/25 Javascript
使用JS进行目录上传(相当于批量上传)
2010/12/05 Javascript
面向对象的Javascript之一(初识Javascript)
2012/01/20 Javascript
js取得url地址参数实例
2013/02/22 Javascript
JavaScript中把数字转换为字符串的程序代码
2013/06/19 Javascript
使用focus方法让光标默认停留在INPUT框
2014/07/29 Javascript
常用的jquery模板插件——jQuery Boilerplate介绍
2014/09/23 Javascript
浅析javascript 定时器
2014/12/23 Javascript
jquery实现点击向下展开菜单项(伸缩导航)效果
2015/08/22 Javascript
总结JavaScript的正则与其他语言的不同之处
2016/08/25 Javascript
基于vue.js实现侧边菜单栏
2017/03/20 Javascript
JS检测window.open打开的窗口是否关闭
2017/06/25 Javascript
js实现数组内数据的上移和下移的实例
2017/11/14 Javascript
解析Json字符串的三种方法日常常用
2018/05/02 Javascript
vue translate peoject实现在线翻译功能【新手必看】
2018/06/07 Javascript
解决vue-cli脚手架打包后vendor文件过大的问题
2018/09/27 Javascript
js this 绑定机制深入详解
2020/04/30 Javascript
Python 内置函数memoryview(obj)的具体用法
2017/11/23 Python
Django接收post前端返回的json格式数据代码实现
2019/07/31 Python
pymysql 开启调试模式的实现
2019/09/24 Python
Python collections中的双向队列deque简单介绍详解
2019/11/04 Python
Python异步编程之协程任务的调度操作实例分析
2020/02/01 Python
基于Tensorflow使用CPU而不用GPU问题的解决
2020/02/07 Python
django创建css文件夹的具体方法
2020/07/31 Python
Python 带星号(* 或 **)的函数参数详解
2021/02/23 Python
OPPO手机官方商城:中国手机市场出货量第一品牌
2017/10/18 全球购物
教师应聘自荐信范文
2014/03/14 职场文书
建筑施工安全责任书
2014/07/24 职场文书
小学国庆节活动方案策划书
2014/09/16 职场文书
学前班幼儿评语大全
2014/12/29 职场文书
Mysql忘记密码解决方法
2022/02/12 MySQL