使用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入门篇之字典
Oct 17 Python
Python实现简单的文件传输与MySQL备份的脚本分享
Jan 03 Python
Python实现购物车功能的方法分析
Nov 10 Python
python+pillow绘制矩阵盖尔圆简单实例
Jan 16 Python
python爬虫的数据库连接问题【推荐】
Jun 25 Python
对python 多个分隔符split 的实例详解
Dec 20 Python
pytorch中的embedding词向量的使用方法
Aug 18 Python
Django框架 查询Extra功能实现解析
Sep 04 Python
Python爬取新型冠状病毒“谣言”新闻进行数据分析
Feb 16 Python
PyCharm无法识别PyQt5的2种解决方法,ModuleNotFoundError: No module named 'pyqt5'
Feb 17 Python
python实点云分割k-means(sklearn)详解
May 28 Python
Python中免验证跳转到内容页的实例代码
Oct 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 中检查或过滤IP地址的实现代码
2011/11/27 PHP
php 获取本地IP代码
2013/06/23 PHP
解析php mysql 事务处理回滚操作(附实例)
2013/08/05 PHP
PHP empty函数报错解决办法
2014/03/06 PHP
两个JavaScript jsFiddle JSBin在线调试器
2010/03/14 Javascript
封装的原生javascript弹出层代码
2010/09/24 Javascript
js优化针对IE6.0起作用(详细整理)
2012/12/25 Javascript
JavaScript创建一个欢迎cookie弹出窗实现代码
2013/03/15 Javascript
DOM节点的替换或修改函数replaceChild()用法实例
2015/01/12 Javascript
ReactNative Image组件使用详解
2017/08/07 Javascript
基于Vue的ajax公共方法(详解)
2018/01/20 Javascript
jQuery实现的电子时钟效果完整示例
2018/04/28 jQuery
JavaScript实现的简单加密解密操作示例
2018/06/01 Javascript
Bootstrap标签页(Tab)插件切换echarts不显示问题的解决
2018/07/13 Javascript
解决layui的radio属性或别的属性没显示出来的问题
2019/09/26 Javascript
[00:35]DOTA2上海特级锦标赛 Newbee战队宣传片
2016/03/03 DOTA
Python Socket实现简单TCP Server/client功能示例
2017/08/05 Python
Python实现将数据写入netCDF4中的方法示例
2018/08/30 Python
python中多个装饰器的调用顺序详解
2019/07/16 Python
Macbook安装Python最新版本、GUI开发环境、图像处理、视频处理环境详解
2020/02/17 Python
pandas数据选取:df[] df.loc[] df.iloc[] df.ix[] df.at[] df.iat[]
2020/04/24 Python
python的json包位置及用法总结
2020/06/21 Python
django表单中的按钮获取数据的实例分析
2020/07/31 Python
Python中实现一行拆多行和多行并一行的示例代码
2020/09/06 Python
python基于pygame实现飞机大作战小游戏
2020/11/19 Python
使用CSS3实现SVG路径描边动画效果入门教程
2019/10/21 HTML / CSS
Linux如何压缩可执行文件
2014/03/27 面试题
应用数学自荐书范文
2013/11/24 职场文书
秋季婚礼证婚词
2014/01/11 职场文书
办公室岗位职责
2015/02/04 职场文书
离婚上诉状范文
2015/05/23 职场文书
Python编解码问题及文本文件处理方法详解
2021/06/20 Python
解析目标检测之IoU
2021/06/26 Python
SQL Server删除表中的重复数据
2022/05/25 SQL Server
MySQL安装失败的原因及解决步骤
2022/06/14 MySQL
react中useState使用:如何实现在当前表格直接更改数据
2022/08/05 Javascript