使用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构造icmp echo请求和实现网络探测器功能代码分享
Jan 10 Python
python抓取网页图片并放到指定文件夹
Apr 24 Python
socket + select 完成伪并发操作的实例
Aug 15 Python
Centos下实现安装Python3.6和Python2共存
Aug 15 Python
Win10下python 2.7.13 安装配置方法图文教程
Sep 18 Python
pyqt5让图片自适应QLabel大小上以及移除已显示的图片方法
Jun 21 Python
连接pandas以及数组转pandas的方法
Jun 28 Python
三步解决python PermissionError: [WinError 5]拒绝访问的情况
Apr 22 Python
python随机模块random的22种函数(小结)
May 15 Python
GitHub上值得推荐的8个python 项目
Oct 30 Python
Python暴力破解Mysql数据的示例
Nov 09 Python
一些让Python代码简洁的实用技巧总结
Aug 23 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调用JAVA的WebService简单实例
2014/03/11 PHP
php文件上传后端处理小技巧
2016/05/22 PHP
php封装的mysqli类完整实例
2016/10/18 PHP
详解如何实现Laravel的服务容器的方法示例
2019/04/15 PHP
laravel框架实现去掉URL中index.php的方法
2019/10/12 PHP
与jquery serializeArray()一起使用的函数,主要来方便提交表单
2011/01/31 Javascript
javascript动态加载三
2012/08/22 Javascript
鼠标事件的screenY,pageY,clientY,layerY,offsetY属性详解
2015/03/12 Javascript
基于jquery实现简单的手风琴特效
2015/11/24 Javascript
JS防止网页被嵌入iframe框架的方法分析
2016/09/13 Javascript
JavaScript排序算法动画演示效果的实现方法
2016/10/18 Javascript
yarn与npm的命令行小结
2016/10/20 Javascript
浅谈JS函数定义方式的区别
2016/10/30 Javascript
Angular 2父子组件数据传递之@ViewChild获取子组件详解
2017/07/04 Javascript
bootstrap table合并行数据并居中对齐效果
2018/10/17 Javascript
JavaScript ES6中的简写语法总结与使用技巧
2018/12/30 Javascript
layui-select动态选中值的例子
2019/09/23 Javascript
vue 组件开发原理与实现方法详解
2019/11/29 Javascript
js实现翻牌小游戏
2020/07/31 Javascript
[03:20]次级联赛厮杀超职业 现超级兵对拆世纪大战
2014/10/30 DOTA
[01:21]DOTA2周边文化主题展 神秘商店火热开售
2017/07/30 DOTA
用Python的Django框架完成视频处理任务的教程
2015/04/02 Python
python实现带错误处理功能的远程文件读取方法
2015/04/29 Python
详解Python的Lambda函数与排序
2016/10/25 Python
详解python运行三种方式
2019/05/13 Python
基于python 取余问题(%)详解
2020/06/03 Python
pycharm 对代码做静态检查操作
2020/06/09 Python
python中的插入排序的简单用法
2021/01/19 Python
HTML5跳转小程序wx-open-launch-weapp的示例代码
2020/07/16 HTML / CSS
意大利宠物用品购物网站:Bauzaar
2018/09/15 全球购物
MATCHESFASHION澳大利亚/亚太地区:英国时尚奢侈品电商
2020/01/14 全球购物
妇女工作先进事迹
2014/08/17 职场文书
离职感谢信怎么写
2015/01/22 职场文书
单位接收函格式
2015/01/30 职场文书
教师党员自我评价2015
2015/03/04 职场文书
用Python提取PDF表格的方法
2021/04/11 Python