Python Matplotlib实现三维数据的散点图绘制

来源:互联网 发布:淘宝上发光闹钟说明书 编辑:程序博客网 时间:2024/05/19 03:20

Python Matplotlib实现三维数据的散点图绘制

一、背景

  近期项目即将开展,计划第一步就是实现数据的可视化,所以先学习一下数据展示相关Demo。选用Python2.7与Matplotlib来实现,平台采用Pycharm,值得一提的是,Matplotlib的安装前首先要安装Numpy包,但是在完成Numpy的安装之后,楼主不能在PyCharm平台下进行自动安装,或者CMD中使用类似pip install Matplotlib,参考网上解决方案后采用直接去官网下载相应的安装包直接运行安装到相关目录下。在此就不赘述了。

二、 参考

  Python语言相对于其他语言对新手较为友好,不用花费太多时间进行语法学习,但是在实际使用的过程中,因为Python中包含有大量的包与资源,在做项目时,对于功能的堆积,实际上Python语言对于新手并不易于理解。相对于Java与C++是需要开发者从底层搭建,可能更易于理解修改(个人意见)。

Matplotlib的gallery部分
  

三、实现过程

  其中就有我们需要参考的部分,也就是mplot3d example code : 2dcollections3d_demo.py。下面贴出其中的代码段。
  

"""=======================Plot 2D data on 3D plot=======================Demonstrates using ax.plot's zdir keyword to plot 2D data onselective axes of a 3D plot."""from mpl_toolkits.mplot3d import Axes3Dimport numpy as npimport matplotlib.pyplot as pltfig = plt.figure()ax = fig.gca(projection='3d')# Plot a sin curve using the x and y axes.x = np.linspace(0, 1, 100)y = np.sin(x * 2 * np.pi) / 2 + 0.5ax.plot(x, y, zs=0, zdir='z', label='curve in (x,y)')# Plot scatterplot data (20 2D points per colour) on the x and z axes.colors = ('r', 'g', 'b', 'k')x = np.random.sample(20*len(colors))y = np.random.sample(20*len(colors))c_list = []for c in colors:    c_list.append([c]*20)# By using zdir='y', the y value of these points is fixed to the zs value 0# and the (x,y) points are plotted on the x and z axes.ax.scatter(x, y, zs=0, zdir='y', c=c_list, label='points in (x,z)')# Make legend, set axes limits and labelsax.legend()ax.set_xlim(0, 1)ax.set_ylim(0, 1)ax.set_zlim(0, 1)ax.set_xlabel('X')ax.set_ylabel('Y')ax.set_zlabel('Z')# Customize the view angle so it's easier to see that the scatter points lie# on the plane y=0ax.view_init(elev=20., azim=-35)plt.show()

   样例的运行结果大致如下:
  
样例演示

  首先样例的数据来自于随机数的产生,但是在我实际使用的过程中,数据是需要预先存储与导入的。因此我添加数据导入部分:

import scipy.io as sio#get the data form F:\matlab.matdata = sio.loadmat('F:\matlab.mat')m = data['data']

  值得一提的是这只是我测试的数据,在实际应用过程中,数据的格式是多种多样的,所以需要做数据格式转化的模块。同时采用.mat数据的格式,用户可以用matlab打开,并对数据进行更改之类的操作。采用这种方法导入后,会自动形成数组。
  
这里写图片描述
  
  如上图所示,是数据在matlab中打开的形式,因为我们需要画出三维散点图,会自动产生3×60的数组,每行代表每一维的数据。贴一张做出的Demo的成果图:
  
这里写图片描述

这里写图片描述
  
  因为我是用Time变量做为Xlabel,同时模拟数据是等时间间距进行采样的,同时想要在不同的时间点采用不同的颜色。因此需要对ax.scatter(x,y,z,c)中的c变量进行更改,可以用变量代替,这样就可以用个循环结构实现颜色的切换功能。

for a in x:    if a == 0.1:        C.append('c')    elif a == 0.2:        C.append('r')    elif a == 0.3:        C.append('y')    elif a == 0.4:        C.append('k')ax.scatter(x, y, z, c=C)

  颜色切换部分代码如下:

import scipy.io as siofrom mpl_toolkits.mplot3d import Axes3Dimport matplotlib.pyplot as pltimport numpy as npdef Singleplot():    data = sio.loadmat('F:\matlab.mat')    m = data['data']    x = m[0]    y = m[1]    z = m[2]    C = []    ax = plt.subplot(111, projection='3d')    for a in x:        if a == 0.1:            C.append('c')        elif a == 0.2:            C.append('r')        elif a == 0.3:            C.append('y')        elif a == 0.4:            C.append('k')    ax.scatter(x, y, z, c=C)    ax.set_xlabel('Time')    ax.set_ylabel('Frequence')    ax.set_zlabel('Amplitude')    plt.show()singleplot()

  需要注意的是Python是属于相对集成度较高的语言,之所以方便使用,是因为存在许多大牛已经完成底层的内容,开发者只需要遵从下载的包中的使用规则,因此过程中对于许多函数不懂的地方,可以用Pycharm的Go to和Declaration功能进入申明区,并且可以从中看到函数的整体介绍,使用语法以及example。因此其中的功能较为有限,如果在短时间内用Python做项目可能对于新手来说,由上到下的形式可能较为简易,但是对于个性化定制功能的话还有待探究。

  第一篇博客。记录一下,本周将学习Logistic回归预测,以及部分TensorFlow的原理与Demo,卡尔曼滤波,和一点数据融合算法。该篇属于数据可视化,还会有3D柱状图的绘制与显示将会尽快整理~

August 7,2017

阅读全文
0 0
原创粉丝点击