Matplotlib mplot3d 工具包简介

The mplot3d toolkit adds simple 3D plotting capabilities to matplotlib by supplying an axes object that can create a 2D projection of a 3D scene. The resulting graph will have the same look and feel as regular 2D plots.

创建Axes3D对象

An Axes3D object is created just like any other axes using the projection=‘3d’ keyword. Create a new matplotlib.figure.Figure and add a new axes to it of type Axes3D:

import matplotlib.pyplot as plt

from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure()

ax = fig.add_subplot(111, projection=’3d’)

New in version 1.0.0: This approach is the preferred method of creating a 3D axes.

Note: Prior to version 1.0.0, the method of creating a 3D axes was di erent. For those using older versions of matplotlib, change ax = fig.add_subplot(111, projection=’3d’) to ax = Axes3D(fig).

要注意的地方

Axes3D展示三维图形时,其初始视图中x,y轴与我们一般看的视图(自己画的时候的视图)是反转的,matlab也是一样。可以通过设置初始视图来改变角度:ax.view_init(30, 35)

Note: 不过这样图形可能会因为旋转而有阴影,也可以通过代码中XY轴互换来实现视图中XY互换。不知道有没有其它方法,如matlab中就有surf(x,y,z);set(gca,'xdir','reverse','ydir','reverse')这样命令来实现这个功能[关于matlab三维图坐标轴原点位置的问题]。

lz总结绘制三维图形一般流程

创建Axes3D对象

fig =plt.figure()

ax =Axes3D(fig)再进行坐标范围设定什么的(可选)

# 计算坐标极限值xs =list(itertools.chain.from_iterable([xi[0] forxi inx]))

x_max, x_min =max(xs), min(xs)

ys =list(itertools.chain.from_iterable([xi[1] forxi inx]))

y_max, y_min =max(ys), min(ys)

zs =list(itertools.chain.from_iterable([xi[2] forxi inx]))

z_max, z_min =max(zs), min(zs)

margin =0.1

再进行绘制,如

plt.scatter(x_new[0], x_new[1], c='r', marker='*', s=50, label='new x')

ax.scatter(xs, ys, zs, c=c, marker=marker, s=50, label=label)

ax.plot_surface(X, Y, Z, rstride=1, cstride=1, label='Discrimination Interface')再进行一些坐标什么的设置

# 设置图形展示效果ax.set_xlim(x_min -margin, x_max +margin)

ax.set_ylim(y_min -margin, y_max +margin)

ax.set_zlim(z_min -margin, z_max +margin)

ax.set_xlabel('x')

ax.set_ylabel('y')

ax.set_zlabel('z')

ax.legend(loc='lower right')

ax.set_title('Plot of class0 vs. class1')

ax.view_init(30, 35)最后显示出来

plt.show()

绘制不同三维图形

Line plots线图

Scatter plots散点图

Axes3D.scatter(xs, ys, zs=0, zdir=u'z', s=20, c=u'b', depthshade=True, *args, **kwargs)

Create a scatter plot

Argument

Description

xs, ys

Positions of data points.

zs

Either an array of the same length as xs andys or a single value to place all points inthe same plane. Default is 0.

zdir

Which direction to use as z (‘x’, ‘y’ or ‘z’)when plotting a 2D set.

s

size in points^2. It is a scalar or an array of thesame length as x andy.

c

a color. c can be a single color format string, or asequence of color specifications of lengthN, or asequence ofN numbers to be mapped to colors using thecmap andnorm specified via kwargs (see below). Notethatc should not be a single numeric RGB or RGBAsequence because that is indistinguishable from an arrayof values to be colormapped.c can be a 2-D array inwhich the rows are RGB or RGBA, however.

depthshade

Whether or not to shade the scatter markers to givethe appearance of depth. Default isTrue.Keyword arguments are passed on to

scatter().

Note: scatter (

x,

y,

s=20,

c=u'b',

marker=u'o',

cmap=None,

norm=None,

vmin=None,

vmax=None,

alpha=None,

linewidths=None,

verts=None,

**kwargs )

Wireframe plots线框图

Surface plots曲面图

参数

x, y, z: x,y,z轴对应的数据。注意z的数据的z.shape是(len(y), len(x)),不然会报错:ValueError: shape mismatch: objects cannot be broadcast to a single shape

rstride    Array row stride (step size), defaults to 10

cstride    Array column stride (step size), defaults to 10

示例1:

import numpy as np

import matplotlib.pyplot as plt

from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure()

ax = Axes3D(fig)

X = np.arange(-4, 4, 0.25)

Y = np.arange(-4, 4, 0.25)

X, Y = np.meshgrid(X, Y)

R = np.sqrt(X**2 + Y**2)

Z = np.sin(R)

ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.cm.hot)

ax.contourf(X, Y, Z, zdir='z', offset=-2, cmap=plt.cm.hot)

ax.set_zlim(-2,2)

# savefig('../figures/plot3d_ex.png',dpi=48)

plt.show()结果图形输出:

示例2:

importnumpy asnp

importmatplotlib.pyplot asplt

frommpl_toolkits.mplot3d importAxes3D

fig =plt.figure()

ax =Axes3D(fig)

x =np.arange(0, 200)

y =np.arange(0, 100)

x, y =np.meshgrid(x, y)

z =np.random.randint(0, 200, size=(100, 200))%3print(z.shape)

# ax.scatter(x, y, z, c='r', marker='.', s=50, label='')ax.plot_surface(x, y, z,label='')

plt.show()

Tri-Surface plots三面图

Contour plots等高线图

Filled contour plots填充等高线图

Polygon plots多边形图

Axes3D.add_collection3d(col, zs=0, zdir=u'z')

Add a 3D collection object to the plot.

2D collection types are converted to a 3D version bymodifying the object and adding z coordinate information.

Supported are:

PolyCollection

LineColleciton

PatchCollection绘图原理是:设置好多面体(如正文体)的顶点坐标和所有面对应的顶点,加上一些属性(如颜色、宽度、透明度)

绘制正方体和四面体示例

#!/usr/bin/env python# -*- coding: utf-8 -*-"""__title__ = ''__author__ = '皮'__mtime__ = '9/27/2015-027'__email__ = 'pipisorry@126.com'"""importmatplotlib.pyplot asplt

frommpl_toolkits.mplot3d.art3d importPoly3DCollection

fig =plt.figure()

ax =fig.gca(projection='3d')

# 正文体顶点和面verts =[(0, 0, 0), (0, 1, 0), (1, 1, 0), (1, 0, 0), (0, 0, 1), (0, 1, 1), (1, 1, 1), (1, 0, 1)]

faces =[[0, 1, 2, 3], [4, 5, 6, 7], [0, 1, 5, 4], [1, 2, 6, 5], [2, 3, 7, 6], [0, 3, 7, 4]]

# 四面体顶点和面# verts = [(0, 0, 0), (1, 0, 0), (1, 1, 0), (1, 0, 1)]# faces = [[0, 1, 2], [0, 1, 3], [0, 2, 3], [1, 2, 3]]# 获得每个面的顶点poly3d =[[verts[vert_id] forvert_id inface] forface infaces]

# print(poly3d)# 绘制顶点x, y, z =zip(*verts)

ax.scatter(x, y, z)

# 绘制多边形面ax.add_collection3d(Poly3DCollection(poly3d, facecolors='w', linewidths=1, alpha=0.3))

# ax.add_collection3d(Line3DCollection(poly3d, colors='k', linewidths=0.5, linestyles=':'))

# 设置图形坐标范围ax.set_xlabel('X')ax.set_xlim3d(-0.5, 1.5)ax.set_ylabel('Y')ax.set_ylim3d(-0.5, 1.5)ax.set_zlabel('Z')ax.set_zlim3d(-0.5, 1.5)plt.show()

绘制结果截图

Bar plots条形图

2D plots in 3D三维图中的二维图

Text文本图

Subplotting子图

matplotlib.mplot3d绘图实例

matplotlib绘制2维高斯分布

importmatplotlib.pyplot asplt

frommpl_toolkits.mplot3d importAxes3D

fig =plt.figure()

ax =Axes3D(fig)

rv =stats.multivariate_normal([0, 0], cov=1)

x, y =np.mgrid[-3:3:.15, -3:3:.15]

ax.plot_surface(x, y, rv.pdf(np.dstack((x, y))), rstride=1, cstride=1)

ax.set_zlim(0, 0.2)

# savefig('../figures/plot3d_ex.png',dpi=48)plt.show()

matplotlib绘制平行z轴的平面

(垂直xy平面的平面)

方程:0*Z + A[0]X + A[1]Y + A[-1] = 0

X =np.arange(x_min-margin, x_max+margin, 0.05)

Z =np.arange(z_min-margin, z_max+margin, 0.05)

X, Z =np.meshgrid(X, Z)

Y = -1/A[1] *(A[0] *X +A[-1])

ax.plot_surface(X, Y, Z, rstride=1, cstride=1, label='Discrimination Interface')

ref:mplot3d tutorial(inside source code)

[mplot3d¶]

python三维绘图工具包_Matplotlib Toolkits:三维绘图工具包matplotlib.mplot3d相关推荐

  1. python 3d图表_matplotlib 三维图表绘制方法简介

    1. python三维图表绘制方法简介 python三维图表的绘制算是二维图表的一个进阶版本,本质上和二维图表的绘制并无差别,唯一的区别在于使用的库略有差异. 相较于二维图表使用的pyplot库,三维 ...

  2. 【python学习】-多张三维图共用一个colorbar(matplotlib绘制)

    多张三维图共用一个colorbar 一张三维图 多张三维图 一张三维图 绘制一张三维图,大概步骤是:导入相关库:生成三维图框,对X,Y数据进行统一网格化,绘制图形,添加colorbar,设置图形其他参 ...

  3. python画三维平面-Python 绘制酷炫的三维图步骤详解

    通常我们用 Python 绘制的都是二维平面图,但有时也需要绘制三维场景图,比如像下面这样的: 这些图怎么做出来呢?今天就来分享下如何一步步绘制出三维矢量(SVG)图. 八面体 我们先以下面这个八面体 ...

  4. python画三维温度散点图-Python 绘制酷炫的三维图步骤详解

    通常我们用 Python 绘制的都是二维平面图,但有时也需要绘制三维场景图,比如像下面这样的: 这些图怎么做出来呢?今天就来分享下如何一步步绘制出三维矢量(SVG)图. 八面体 我们先以下面这个八面体 ...

  5. python画三维散点图-Python 绘制酷炫的三维图步骤详解

    通常我们用 Python 绘制的都是二维平面图,但有时也需要绘制三维场景图,比如像下面这样的: 这些图怎么做出来呢?今天就来分享下如何一步步绘制出三维矢量(SVG)图. 八面体 我们先以下面这个八面体 ...

  6. python画三维图-Python 绘制酷炫的三维图步骤详解

    通常我们用 Python 绘制的都是二维平面图,但有时也需要绘制三维场景图,比如像下面这样的: 这些图怎么做出来呢?今天就来分享下如何一步步绘制出三维矢量(SVG)图. 八面体 我们先以下面这个八面体 ...

  7. python画3d图-Python 绘制酷炫的三维图步骤详解

    通常我们用 Python 绘制的都是二维平面图,但有时也需要绘制三维场景图,比如像下面这样的: 这些图怎么做出来呢?今天就来分享下如何一步步绘制出三维矢量(SVG)图. 八面体 我们先以下面这个八面体 ...

  8. 使用Python的Cufflinks库创建三维散点图

    使用Python的Cufflinks库创建三维散点图 在数据可视化中,三维散点图是一种常用的图形展示方式.如果您正在寻找一种方便易用的数据可视化工具来创建三维散点图,那么Cufflinks就是一个不错 ...

  9. python画三维立体图-Python 绘制酷炫的三维图步骤详解

    通常我们用 Python 绘制的都是二维平面图,但有时也需要绘制三维场景图,比如像下面这样的: 这些图怎么做出来呢?今天就来分享下如何一步步绘制出三维矢量(SVG)图. 八面体 我们先以下面这个八面体 ...

最新文章

  1. win7右键新建文件夹不见了
  2. UVA 1471 Defense Lines 防线 (LIS变形)
  3. 苹果系统下如何粘贴复制?
  4. 穷学计算机富学金融家里有矿,穷学IT,富学金融?亲身体验告诉你IT真的是一个不用拼爹的行业...
  5. [zjoi2017]仙人掌
  6. 画世界上传图片提交到服务器_【MUI】选择图片并上传至服务器
  7. java学习(102):arraylist的查询和删除
  8. linux通过I2C地址查看设备名称
  9. 小米新机“Davinci”跑分曝光: 单核成绩达2574分
  10. c语言程序装萝卜,萝卜花园练习win7系统安装SkyDrive的图文步骤
  11. 【报告分享】迈向万亿市场的直播电商-毕马威+阿里研究院.pdf(附下载链接)...
  12. 绝对值编码器 c语言,绝对式光电编码器
  13. C语言选择题(含答案)
  14. 如何减小电压跟随器输出电阻_运算放大器和比较器还傻傻分不清楚?一篇图文教你轻松辨认...
  15. hdmi 计算机 接口类型,四大常用视频接口对比,你的电脑是哪种接口?
  16. html取消父元素样式,CSS以防止子元素继承父样式
  17. 希尔排序--简单易懂图解
  18. 2019 全年中国马拉松赛事日历表
  19. ajax请求在ie浏览器上的兼容性问题
  20. My Heart Will Go On(我心永恒)

热门文章

  1. 大数据基础课04 大数据开发必备工具和来源
  2. 如何自己租GPU服务器(阿里云)跑pytorch代码
  3. 汽车的违章停车检测系统
  4. 面试直通卡大放送,微软面试官带你揭秘面试潜规则!
  5. 那个网络工程师技能图谱2.0版来了,再看看你会多少
  6. 如何卸载Android自带系统应用
  7. mysql dml语句 先读取在更新_事务的4个特性——ACID(原子性、一致性、隔离性和持久性)、更新丢失问题...
  8. DataGrid自动调整行高
  9. 什么是udp攻击?udp攻击的基本原理是什么
  10. Angular响应式开发中报错Property 'map' does not exist on type 'Observable'.引用rxjs也没用。