天天看點

python - 繪制與資料相關的标記和顔色的3D散點圖

大家可以先參考官方示範文檔:

效果圖:

python - 繪制與資料相關的标記和顔色的3D散點圖
'''
==============
3D scatterplot
==============
Demonstration of a basic scatterplot in 3D.
'''
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()      

以上是官網上的代碼示例及示範結果,下面分享下本文代碼示例。

本執行個體需要導入第三包:

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

然後繪圖:

ax = plt.figure().add_subplot(111, projection = '3d')
#基于ax變量繪制三維圖
#xs表示x方向的變量
#ys表示y方向的變量
#zs表示z方向的變量,這三個方向上的變量都可以用list的形式表示
#m表示點的形式,o是圓形的點,^是三角形(marker)
#c表示顔色(color for short)
ax.scatter(xs, ys, zs, c = 'r', marker = '^') #點為紅色三角形
 
#設定坐标軸
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
 
#顯示圖像
plt.show()      

注:

上面的

ax = plt.figure().add_subplot(111, projection = '3d')      
fig = plt.figure()
ax = fig.add_subplot(111, projection = '3d')      
ax.scatter(df['f1'], df['f2'], df['f3'], c=df['y'], s=100)