可视化

matplotlib手册(12) - 绘制3D图形

2018-06-27  本文已影响40人  橘猫吃不胖

想画个3D的图形,这里看看matplotlib怎样绘制3D图形。
官方文档地址:The mplot3d Toolkit

这里有一个版本的问题,先来看看怎样查看matplotlib的版本

# -*- coding: utf-8 -*-
"""
Created on 2018-06-26 20:45:40

@author: guiyang.yu

@description: 3D实例
1.查看matplotlib版本
"""

import matplotlib

print(matplotlib.__version__)

看这个版本是因为,1.0之后的版本和老的版本使用方式不太一样,这里记录下。

创建3D坐标轴
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

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

这里主要是是创建一个面板,然后使用projection参数指定为‘3d’就行了
经测试,Axes3D没用到,不引入也可以


画一条线

然后我们可以在坐标轴上画一条线,依然是使用plot

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

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
plt.plot([0,1],[0,1],[0,1])

其他的用法都是一样的

plt.plot([0,1],[0,1],[0,1],marker='*',c='r')

我们还可以设置3个坐标轴的一些属性

import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot([0,1],[0,1],[0,1],marker='*',c='r',markerfacecolor='g',markeredgecolor='g')

ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')

ax.set_xlim(0,2)
ax.set_ylim(0,2)
ax.set_zlim(0,1)
绘制散点图

和上面的思路一样,我们使用scatter来绘制散点图
参考matplotlib手册(11) - 散点图

import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
#ax.plot([0,1],[0,1],[0,1],marker='*',c='r',markerfacecolor='g',markeredgecolor='g')
ax.scatter([0.5,1,2],[0.5,1,2],[0.5,1,1])

ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')

ax.set_xlim(0,2)
ax.set_ylim(0,2)
ax.set_zlim(0,1)
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
#ax.plot([0,1],[0,1],[0,1],marker='*',c='r',markerfacecolor='g',markeredgecolor='g')

data = np.random.randint(0,100,size=[3,10,10])
x,y,z = data[0],data[1],data[2]

ax.scatter(x[:1],y[:1],z[:1],c='r')
ax.scatter(x[1:2],y[1:2],z[1:2],c='y')
ax.scatter(x[2:3],y[2:3],z[2:3],c='b')

ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
上一篇 下一篇

猜你喜欢

热点阅读