1. 程式人生 > >Matplotlib Toolkits:三維繪圖工具包matplotlib.mplot3d

Matplotlib Toolkits:三維繪圖工具包matplotlib.mplot3d

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] for xi in x]))
x_max, x_min = max(xs), min(xs)
ys = list(itertools.chain.from_iterable([xi[1] for xi in x]))
y_max, y_min = max(ys), min(ys)
zs = list
(itertools.chain.from_iterable([xi[2] for xi in x])) 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

ArgumentDescription
xs, ysPositions of data points.
zsEither an array of the same length as xs andys or a single value to place all points inthe same plane. Default is 0.
zdirWhich direction to use as z (‘x’, ‘y’ or ‘z’)when plotting a 2D set.
ssize in points^2. It is a scalar or an array of thesame length as x andy.
ca 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.
depthshadeWhether or not to shade the scatter markers to givethe appearance of depth. Default isTrue.
Keyword arguments are passed on to scatter().Returns a Patch3DCollectionNote: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)
../../_images/scatter3d_demo1.png

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:

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

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))%3
print(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__ = '[email protected]'"""
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.art3d import Poly3DCollection

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] for vert_id in face] for face in faces]
# 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維高斯分佈

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
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')

[mplot3d]

相關推薦

Matplotlib Toolkits繪圖工具matplotlib.mplot3d

Matplotlib mplot3d 工具包簡介The mplot3d toolkit adds simple 3D plotting capabilities to matplotlib by supplying an axes object that can create

Qt學習繪圖之OpenGL和Qt的結合

        OpenGL是繪製三維圖形的標準API。Qt應用程式可以使用QtOpenGL模組繪製三維圖形,該模組依賴於系統的OpenGL庫。Qt OpenGL模組提供QGLWidget類,可以通過對它子類化,並使用OpenGL命令開發出自己的視窗部件。對許多三維應用程式

區塊鏈技術基礎語言(十)Go語言常用工具(下)

原文連結:區塊鏈技術基礎語言(三十):Go語言常用工具包(下) 一、JSON處理 JSON(JavaScript Object Notation)是一種輕量級的資料交換格式,方便人們閱讀和編寫,也方便程式地解析和生成。雖然JSON是JavaScript的子集,但其格式完全獨立於程式語言,表現

Python繪圖--Matplotlib

Python三維繪圖 在遇到三維資料時,三維影象能給我們對資料帶來更加深入地理解。python的matplotlib庫就包含了豐富的三維繪圖工具。 1.建立三維座標軸物件Axes3D 建立Axes3

Windows Phone開發(19)透視效果

end 理論知識 form 之間 3d模型 中間 第一個 一個 好的 三維效果也可以叫透視效果,所以,我幹脆叫三維透視效果。理論知識少講,直接用例開場吧,因為這個三維效果其實很簡單,比上一節中的變換更省事,不信?一起來做一做練習吧。 練習一:把對象沿Y軸旋轉45度。 默認情

繪圖工具類詳解

style red ict 貝塞爾 字號 清晰 mask startx 分享 1.相關方法詳解 1)Paint(畫筆): 就是畫筆,用於設置繪制風格,如:線寬(筆觸粗細),顏色,透明度和填充風格等 直接使用無參構造方法就可以創建Paint實例: Paint paint =

45.Qt openGL實現繪圖

窗口 err lin span protected 調用 event header 實現 main.cpp #include <QApplication> #include <iostream> #include "tetrahea

Python篇散點圖scatter介紹

    ##畫個簡單三維圖 import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D ax = plt.figure().add_subplot(111, pr

matlab的繪圖和四繪圖

一、三維繪圖 1.曲線圖 plot3(X1,Y1,Z1,...):以預設線性屬性繪製三維點集(X1,Y1,Z1)確定的曲線 plot3(X1,Y1,Z1,LineSpec):以引數LineSpec確定的線性屬性繪製三維點集 plot3(X1,Y1,Z1,'PropertyN

GMT繪圖有BUG? 修復它!

前期一篇文章:Modern GMT Series:Slice in 3D View (三維切片圖)中提到了在科研作圖中會經常遇到三維作圖的問題,而且GMT可以做三維圖且匯出的圖片質量非常高!但是也提到了當前GMT版本中的三維繪圖存在漏洞。主要兩個問題:(1)切片位置錯亂;(2)三維文字映象。就這兩個問題極

python matplotlib模組——繪製圖形、資料散點圖

python matplotlib模組,是擴充套件的MATLAB的一個繪圖工具庫。他可以繪製各種圖形,可是最近最的一個小程式,得到一些三維的資料點圖,就學習了下python中的matplotlib模組,

python3.6 + tensorflow入門點擬合平面

參考連結: http://wiki.jikexueyuan.com/project/tensorflow-zh/get_started/introduction.html 程式碼: # -*- coding: utf-8 -*- """ Created on Fri Dec 21 14:

MATLAB中surf與scatter3不能同時繪圖解決辦法

最近在用MATLAB畫圖時遇見了一個非常有意思的事,用surf畫一個面,同時在這個fig上用scatter3畫一些點,當然這是在三維空間中,這時你會發現最後只有一個圖在fig上,當然,這裡我們用了ho

pcl模型obj格式轉成pcl常用點雲處理格式.pcd+matlab:.ply.pcd+其他.stl,.obj,.ply等格式互相轉化方法

①程式碼: #include <pcl/io/io.h> #include <pcl/io/pcd_io.h> #include <pcl/io/obj_io.h>

roosephu 考題之一 偏序

            roosephu的考題,水題倒還是水,難題難的無語。             三維偏序,本來是以前省隊集訓的時候遇到的東西,那時候是徹底被噁心到了,沒寫出來,而這一次仍舊被小小的噁心到了。             原題是給三個1~n的排列列,求三個

MFC+OpenGL繪圖(二)——開啟一個STL檔案並顯示

    在上一節中,我們主要介紹瞭如何在VS2013平臺上利用OpenGL庫函式開發一個簡單的三維繪圖軟體。但那個軟體只是搭建一個簡單的三維繪圖軟體平臺,除了實現影象簡單的平移、旋轉、縮放功能外並沒有什麼實際的作用,但不用擔心,那只是三維圖形軟體繪製的基礎,為了實現一個完整的

告別傳統工業網際網路,提高數字管控思維組態分散式能源站

前言 在網路迅速發展的今天,人們的交流已經不再僅限與面對面,一個視訊通話就能拉近彼此之間的距離,而在工業管控上卻不僅僅侷限於實時視訊流的監控,HTML 本身擁有強大的 web 元件可供我們去實施一些好玩的例子,甚至加上一些簡單有趣的動畫和實時資料的對接,效果上可不止提高了一個水平。加上現如今已經啟動許久的&n

python matplotlibmat mplot3d工具 檢視透視取消

https://stackoverflow.com/questions/23840756/how-to-disable-perspective-in-mplot3d 簡單的解決方法是 ax = fig.add_subplot(111, projection='3d', proj_type='ortho')

DICOMdcm4che工具怎樣壓縮dcm文件探討(續篇)

fff dcm4chee ret int 無法 ddc too all tail 背景 前段時間博文 DICOM:dcm4che工具包怎樣壓縮dcm文件探討(前篇)提到了一個問題:“利用dcm4che工具包中的dcm2dcm來進行dcm文件的壓縮和加壓

THULAC一個高效的中文詞法分析工具(z'z)

bsp 準確率 ext 效果 python3 nlp org 集成 的人 網址:http://thulac.thunlp.org/ THULAC(THU Lexical Analyzer for Chinese)由清華大學自然語言處理與社會人文計算實驗室研制推出的一套中文詞