使用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采集博客中上传的QQ截图文件
Jul 18 Python
Python中操作mysql的pymysql模块详解
Sep 13 Python
python 获取网页编码方式实现代码
Mar 11 Python
Python 类的继承实例详解
Mar 25 Python
查找python项目依赖并生成requirements.txt的方法
Jul 10 Python
python调用opencv实现猫脸检测功能
Jan 15 Python
快速解决pyqt5窗体关闭后子线程不同时退出的问题
Jun 19 Python
python字符串替换re.sub()实例解析
Feb 09 Python
Python 解决火狐浏览器不弹出下载框直接下载的问题
Mar 09 Python
python实现人机五子棋
Mar 25 Python
Python3实现打印任意宽度的菱形代码
Apr 12 Python
Python利用Turtle绘制哆啦A梦和小猪佩奇
Apr 04 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报表之jpgraph柱状图实例代码
2011/08/22 PHP
PHP数组及条件,循环语句学习
2012/11/11 PHP
PHP处理二进制数据的实现方法
2016/06/13 PHP
php好代码风格的阶段性总结
2016/06/25 PHP
Thinkphp3.2.3整合phpqrcode生成带logo的二维码
2016/07/21 PHP
示例详解Laravel重置密码代码重构
2016/08/10 PHP
PHP PDOStatement::getColumnMeta讲解
2019/02/01 PHP
多个iframe自动调整大小的问题
2006/09/18 Javascript
JavaScript 模仿vbs中的 DateAdd() 函数的代码
2007/08/13 Javascript
jquery在Chrome下获取图片的长宽问题解决
2013/03/20 Javascript
jquery获得keycode的示例代码
2013/12/30 Javascript
jQuery循环动画与获取组件尺寸的方法
2015/02/02 Javascript
jQuery DOM删除节点操作指南
2015/03/03 Javascript
javascript中undefined与null的区别
2015/08/16 Javascript
jQuery+CSS实现一个侧滑导航菜单代码
2016/05/09 Javascript
Node.js DES加密的简单实现
2016/07/07 Javascript
JavaScript每天必学之数组和对象部分
2016/09/17 Javascript
JavaScript获取tr td 的三种方式全面总结(推荐)
2017/08/15 Javascript
如何自定义微信小程序tabbar上边框的颜色
2019/07/09 Javascript
elementUI 动态生成几行几列的方法示例
2019/07/11 Javascript
详解vue beforeEach 死循环问题解决方法
2020/02/25 Javascript
微信小程序学习总结(一)项目创建与目录结构分析
2020/06/04 Javascript
python Django连接MySQL数据库做增删改查
2013/11/07 Python
Python实现求两个csv文件交集的方法
2017/09/06 Python
Python实现将数据写入netCDF4中的方法示例
2018/08/30 Python
Python内置函数property()如何使用
2020/09/01 Python
如何通过python检查文件是否被占用
2020/12/18 Python
英国领先的互联网葡萄酒礼品商:Vintage Wine & Port
2019/05/24 全球购物
南京迈特望C/C++面试题
2012/07/09 面试题
网友共享的几个面试题关于Java和Unix等方面的
2016/09/08 面试题
保安员岗位职责
2013/11/17 职场文书
上课迟到检讨书
2014/02/19 职场文书
经济贸易专业自荐信
2014/06/11 职场文书
行政求职信
2014/07/04 职场文书
2015年综治维稳工作总结
2015/04/07 职场文书
mysql优化之query_cache_limit参数说明
2021/07/01 MySQL