python 绘制等三维图_python绘制三维图

2023-11-11 13:21
文章标签 python 绘制 三维图

本文主要是介绍python 绘制等三维图_python绘制三维图,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

作者:桂。

时间:2017-04-27 23:24:55

本文仅仅梳理最基本的绘图方法。

一、初始化

假设已经安装了matplotlib工具包。

利用matplotlib.figure.Figure创建一个图框:

import matplotlib.pyplot as plt

from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure()

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

1085343-20170427232821475-1581674640.png

二、直线绘制(Line plots)

基本用法:

ax.plot(x,y,z,label=' ')

code:

import matplotlib as mpl

from mpl_toolkits.mplot3d import Axes3D

import numpy as np

import matplotlib.pyplot as plt

mpl.rcParams['legend.fontsize'] = 10

fig = plt.figure()

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

theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)

z = np.linspace(-2, 2, 100)

r = z**2 + 1

x = r * np.sin(theta)

y = r * np.cos(theta)

ax.plot(x, y, z, label='parametric curve')

ax.legend()

plt.show()

1085343-20170427233438506-816080794.png

三、散点绘制(Scatter plots)

基本用法:

ax.scatter(xs, ys, zs, s=20, c=None, depthshade=True, *args, *kwargs)

xs,ys,zs:输入数据;

s:scatter点的尺寸

c:颜色,如c = 'r'就是红色;

depthshase:透明化,True为透明,默认为True,False为不透明

*args等为扩展变量,如maker = 'o',则scatter结果为’o‘的形状

code:

from mpl_toolkits.mplot3d import Axes3D

import matplotlib.pyplot as plt

import numpy as np

def randrange(n, vmin, vmax):

'''

Helper function to make an array of random numbers having shape (n, )

with each number distributed Uniform(vmin, vmax).

'''

return (vmax - vmin)*np.random.rand(n) + vmin

fig = plt.figure()

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

n = 100

# For each set of style and range settings, plot n random points in the box

# defined by x in [23, 32], y in [0, 100], z in [zlow, zhigh].

for c, m, zlow, zhigh in [('r', 'o', -50, -25), ('b', '^', -30, -5)]:

xs = randrange(n, 23, 32)

ys = randrange(n, 0, 100)

zs = randrange(n, zlow, zhigh)

ax.scatter(xs, ys, zs, c=c, marker=m)

ax.set_xlabel('X Label')

ax.set_ylabel('Y Label')

ax.set_zlabel('Z Label')

plt.show()

1085343-20170427234600069-1123635540.png

四、线框图(Wireframe plots)

基本用法:

ax.plot_wireframe(X, Y, Z, *args, **kwargs)

X,Y,Z:输入数据

rstride:行步长

cstride:列步长

rcount:行数上限

ccount:列数上限

code:

from mpl_toolkits.mplot3d import axes3d

import matplotlib.pyplot as plt

fig = plt.figure()

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

# Grab some test data.

X, Y, Z = axes3d.get_test_data(0.05)

# Plot a basic wireframe.

ax.plot_wireframe(X, Y, Z, rstride=10, cstride=10)

plt.show()

1085343-20170427235353975-1165295870.png

五、表面图(Surface plots)

基本用法:

ax.plot_surface(X, Y, Z, *args, **kwargs)

X,Y,Z:数据

rstride、cstride、rcount、ccount:同Wireframe plots定义

color:表面颜色

cmap:图层

code:

from mpl_toolkits.mplot3d import Axes3D

import matplotlib.pyplot as plt

from matplotlib import cm

from matplotlib.ticker import LinearLocator, FormatStrFormatter

import numpy as np

fig = plt.figure()

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

# Make data.

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

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

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

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

Z = np.sin(R)

# Plot the surface.

surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm,

linewidth=0, antialiased=False)

# Customize the z axis.

ax.set_zlim(-1.01, 1.01)

ax.zaxis.set_major_locator(LinearLocator(10))

ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

# Add a color bar which maps values to colors.

fig.colorbar(surf, shrink=0.5, aspect=5)

plt.show()

1085343-20170427235619381-1099728432.png

六、三角表面图(Tri-Surface plots)

基本用法:

ax.plot_trisurf(*args, **kwargs)

X,Y,Z:数据

其他参数类似surface-plot

code:

from mpl_toolkits.mplot3d import Axes3D

import matplotlib.pyplot as plt

import numpy as np

n_radii = 8

n_angles = 36

# Make radii and angles spaces (radius r=0 omitted to eliminate duplication).

radii = np.linspace(0.125, 1.0, n_radii)

angles = np.linspace(0, 2*np.pi, n_angles, endpoint=False)

# Repeat all angles for each radius.

angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1)

# Convert polar (radii, angles) coords to cartesian (x, y) coords.

# (0, 0) is manually added at this stage, so there will be no duplicate

# points in the (x, y) plane.

x = np.append(0, (radii*np.cos(angles)).flatten())

y = np.append(0, (radii*np.sin(angles)).flatten())

# Compute z to make the pringle surface.

z = np.sin(-x*y)

fig = plt.figure()

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

ax.plot_trisurf(x, y, z, linewidth=0.2, antialiased=True)

plt.show()

1085343-20170428064410412-2144400745.png

七、等高线(Contour plots)

基本用法:

ax.contour(X, Y, Z, *args, **kwargs)

code:

from mpl_toolkits.mplot3d import axes3d

import matplotlib.pyplot as plt

from matplotlib import cm

fig = plt.figure()

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

X, Y, Z = axes3d.get_test_data(0.05)

cset = ax.contour(X, Y, Z, cmap=cm.coolwarm)

ax.clabel(cset, fontsize=9, inline=1)

plt.show()

1085343-20170428064857709-331889624.png

二维的等高线,同样可以配合三维表面图一起绘制:

code:

from mpl_toolkits.mplot3d import axes3d

from mpl_toolkits.mplot3d import axes3d

import matplotlib.pyplot as plt

from matplotlib import cm

fig = plt.figure()

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

X, Y, Z = axes3d.get_test_data(0.05)

ax.plot_surface(X, Y, Z, rstride=8, cstride=8, alpha=0.3)

cset = ax.contour(X, Y, Z, zdir='z', offset=-100, cmap=cm.coolwarm)

cset = ax.contour(X, Y, Z, zdir='x', offset=-40, cmap=cm.coolwarm)

cset = ax.contour(X, Y, Z, zdir='y', offset=40, cmap=cm.coolwarm)

ax.set_xlabel('X')

ax.set_xlim(-40, 40)

ax.set_ylabel('Y')

ax.set_ylim(-40, 40)

ax.set_zlabel('Z')

ax.set_zlim(-100, 100)

plt.show()

1085343-20170428065239631-897876346.png

也可以是三维等高线在二维平面的投影:

code:

from mpl_toolkits.mplot3d import axes3d

import matplotlib.pyplot as plt

from matplotlib import cm

fig = plt.figure()

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

X, Y, Z = axes3d.get_test_data(0.05)

ax.plot_surface(X, Y, Z, rstride=8, cstride=8, alpha=0.3)

cset = ax.contourf(X, Y, Z, zdir='z', offset=-100, cmap=cm.coolwarm)

cset = ax.contourf(X, Y, Z, zdir='x', offset=-40, cmap=cm.coolwarm)

cset = ax.contourf(X, Y, Z, zdir='y', offset=40, cmap=cm.coolwarm)

ax.set_xlabel('X')

ax.set_xlim(-40, 40)

ax.set_ylabel('Y')

ax.set_ylim(-40, 40)

ax.set_zlabel('Z')

ax.set_zlim(-100, 100)

plt.show()

1085343-20170428065622537-1308648947.png

八、Bar plots(条形图)

基本用法:

ax.bar(left, height, zs=0, zdir='z', *args, **kwargs

x,y,zs = z,数据

zdir:条形图平面化的方向,具体可以对应代码理解。

code:

from mpl_toolkits.mplot3d import Axes3D

import matplotlib.pyplot as plt

import numpy as np

fig = plt.figure()

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

for c, z in zip(['r', 'g', 'b', 'y'], [30, 20, 10, 0]):

xs = np.arange(20)

ys = np.random.rand(20)

# You can provide either a single color or an array. To demonstrate this,

# the first bar of each set will be colored cyan.

cs = [c] * len(xs)

cs[0] = 'c'

ax.bar(xs, ys, zs=z, zdir='y', color=cs, alpha=0.8)

ax.set_xlabel('X')

ax.set_ylabel('Y')

ax.set_zlabel('Z')

plt.show()

1085343-20170428065810647-854711136.png

九、子图绘制(subplot)

A-不同的2-D图形,分布在3-D空间,其实就是投影空间不空,对应code:

from mpl_toolkits.mplot3d import Axes3D

import numpy as np

import matplotlib.pyplot as plt

fig = 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.5

ax.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 labels

ax.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')

1085343-20170428070320694-1392528345.png

B-子图Subplot用法

与MATLAB不同的是,如果一个四子图效果,如:

1085343-20170428071243834-1968412328.png

MATLAB:

subplot(2,2,1)

subplot(2,2,2)

subplot(2,2,[3,4])

Python:

subplot(2,2,1)

subplot(2,2,2)

subplot(2,1,2)

code:

import matplotlib.pyplot as plt

from mpl_toolkits.mplot3d.axes3d import Axes3D, get_test_data

from matplotlib import cm

import numpy as np

# set up a figure twice as wide as it is tall

fig = plt.figure(figsize=plt.figaspect(0.5))

#===============

# First subplot

#===============

# set up the axes for the first plot

ax = fig.add_subplot(2, 2, 1, projection='3d')

# plot a 3D surface like in the example mplot3d/surface3d_demo

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

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

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

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

Z = np.sin(R)

surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm,

linewidth=0, antialiased=False)

ax.set_zlim(-1.01, 1.01)

fig.colorbar(surf, shrink=0.5, aspect=10)

#===============

# Second subplot

#===============

# set up the axes for the second plot

ax = fig.add_subplot(2,1,2, projection='3d')

# plot a 3D wireframe like in the example mplot3d/wire3d_demo

X, Y, Z = get_test_data(0.05)

ax.plot_wireframe(X, Y, Z, rstride=10, cstride=10)

plt.show()

1085343-20170428071408428-487524193.png

补充:

文本注释的基本用法:

code:

from mpl_toolkits.mplot3d import Axes3D

import matplotlib.pyplot as plt

fig = plt.figure()

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

# Demo 1: zdir

zdirs = (None, 'x', 'y', 'z', (1, 1, 0), (1, 1, 1))

xs = (1, 4, 4, 9, 4, 1)

ys = (2, 5, 8, 10, 1, 2)

zs = (10, 3, 8, 9, 1, 8)

for zdir, x, y, z in zip(zdirs, xs, ys, zs):

label = '(%d, %d, %d), dir=%s' % (x, y, z, zdir)

ax.text(x, y, z, label, zdir)

# Demo 2: color

ax.text(9, 0, 0, "red", color='red')

# Demo 3: text2D

# Placement 0, 0 would be the bottom left, 1, 1 would be the top right.

ax.text2D(0.05, 0.95, "2D Text", transform=ax.transAxes)

# Tweaking display region and labels

ax.set_xlim(0, 10)

ax.set_ylim(0, 10)

ax.set_zlim(0, 10)

ax.set_xlabel('X axis')

ax.set_ylabel('Y axis')

ax.set_zlabel('Z axis')

plt.show()

1085343-20170428070440772-788186162.png

参考:

这篇关于python 绘制等三维图_python绘制三维图的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/390354

相关文章

使用Python绘制蛇年春节祝福艺术图

《使用Python绘制蛇年春节祝福艺术图》:本文主要介绍如何使用Python的Matplotlib库绘制一幅富有创意的“蛇年有福”艺术图,这幅图结合了数字,蛇形,花朵等装饰,需要的可以参考下... 目录1. 绘图的基本概念2. 准备工作3. 实现代码解析3.1 设置绘图画布3.2 绘制数字“2025”3.3

python使用watchdog实现文件资源监控

《python使用watchdog实现文件资源监控》watchdog支持跨平台文件资源监控,可以检测指定文件夹下文件及文件夹变动,下面我们来看看Python如何使用watchdog实现文件资源监控吧... python文件监控库watchdogs简介随着Python在各种应用领域中的广泛使用,其生态环境也

Python中构建终端应用界面利器Blessed模块的使用

《Python中构建终端应用界面利器Blessed模块的使用》Blessed库作为一个轻量级且功能强大的解决方案,开始在开发者中赢得口碑,今天,我们就一起来探索一下它是如何让终端UI开发变得轻松而高... 目录一、安装与配置:简单、快速、无障碍二、基本功能:从彩色文本到动态交互1. 显示基本内容2. 创建链

Java调用Python代码的几种方法小结

《Java调用Python代码的几种方法小结》Python语言有丰富的系统管理、数据处理、统计类软件包,因此从java应用中调用Python代码的需求很常见、实用,本文介绍几种方法从java调用Pyt... 目录引言Java core使用ProcessBuilder使用Java脚本引擎总结引言python

python 字典d[k]中key不存在的解决方案

《python字典d[k]中key不存在的解决方案》本文主要介绍了在Python中处理字典键不存在时获取默认值的两种方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,... 目录defaultdict:处理找不到的键的一个选择特殊方法__missing__有时候为了方便起见,

使用Python绘制可爱的招财猫

《使用Python绘制可爱的招财猫》招财猫,也被称为“幸运猫”,是一种象征财富和好运的吉祥物,经常出现在亚洲文化的商店、餐厅和家庭中,今天,我将带你用Python和matplotlib库从零开始绘制一... 目录1. 为什么选择用 python 绘制?2. 绘图的基本概念3. 实现代码解析3.1 设置绘图画

Python pyinstaller实现图形化打包工具

《Pythonpyinstaller实现图形化打包工具》:本文主要介绍一个使用PythonPYQT5制作的关于pyinstaller打包工具,代替传统的cmd黑窗口模式打包页面,实现更快捷方便的... 目录1.简介2.运行效果3.相关源码1.简介一个使用python PYQT5制作的关于pyinstall

使用Python实现大文件切片上传及断点续传的方法

《使用Python实现大文件切片上传及断点续传的方法》本文介绍了使用Python实现大文件切片上传及断点续传的方法,包括功能模块划分(获取上传文件接口状态、临时文件夹状态信息、切片上传、切片合并)、整... 目录概要整体架构流程技术细节获取上传文件状态接口获取临时文件夹状态信息接口切片上传功能文件合并功能小

python实现自动登录12306自动抢票功能

《python实现自动登录12306自动抢票功能》随着互联网技术的发展,越来越多的人选择通过网络平台购票,特别是在中国,12306作为官方火车票预订平台,承担了巨大的访问量,对于热门线路或者节假日出行... 目录一、遇到的问题?二、改进三、进阶–展望总结一、遇到的问题?1.url-正确的表头:就是首先ur

基于Python实现PDF动画翻页效果的阅读器

《基于Python实现PDF动画翻页效果的阅读器》在这篇博客中,我们将深入分析一个基于wxPython实现的PDF阅读器程序,该程序支持加载PDF文件并显示页面内容,同时支持页面切换动画效果,文中有详... 目录全部代码代码结构初始化 UI 界面加载 PDF 文件显示 PDF 页面页面切换动画运行效果总结主