python3 绘制三维空间圆的散点图

python 没有方便好用的直接画圆的方法,一般而言,都是使用参数方程画圆,要在三维空间画圆,可利用三维空间中圆的参数方程:
图片来源于 http://blog.sina.com.cn/s/blog_6496e38e0102vi7e.html

{ x ( θ ) = c 1 + r c o s ( θ ) a 1 + r s i n ( θ ) b 1 y ( θ ) = c 2 + r c o s ( θ ) a 2 + r s i n ( θ ) b 2 z ( θ ) = c 3 + r c o s ( θ ) a 3 + r s i n ( θ ) b 3 \left\{ \begin{array}{cl} x(\theta)=c_1+r cos(\theta)a_1 + r sin(\theta)b_1 \\ y(\theta)=c_2+r cos(\theta)a_2+ r sin(\theta)b_2 \\ z(\theta)=c_3+r cos(\theta)a_3 + r sin(\theta)b_3 \end{array} \right . x(θ)=c1+rcos(θ)a1+rsin(θ)b1y(θ)=c2+rcos(θ)a2+rsin(θ)b2z(θ)=c3+rcos(θ)a3+rsin(θ)b3

其中 ( a 1 , a 2 , a 3 ) (a_1, a_2, a_3) (a1,a2,a3) ( b 1 , b 2 , b 3 ) (b_1, b_2, b_3) (b1,b2,b3)代表圆面内的单位向量 a ⃗ \vec{a} a b ⃗ \vec{b} b ,它们相互垂直,且都垂直于圆的法向量 n ⃗ \vec{n} n ( c 1 , c 2 , c 3 ) (c_1, c_2, c_3) (c1,c2,c3)为圆心坐标。

因为这里我的需求是生成空间圆的散点图(带噪声)用于聚类试验用,所以代码里加了一些噪声。

在这里插入图片描述

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D # 绘制3d散点图

# center 为圆心,n 为圆法向量,noise 为噪声范围, r为半径
def generate_3D_circle(sample_num = 100, r = 1.8, noise = 0.3, center = [0, 0, 0], n = [1, 0, 0]):
    sample = np.linspace(-np.pi, np.pi, sample_num)
    
    a = np.cross(n, [1, 0, 0]) # np.cross(), 向量叉积
    if np.all(a == 0):  # a 是否为0向量
        a = np.cross(n, [0, 1, 0])

    b = np.cross(n, a)  

    # 归一化a,b(圆面两个互垂直向量)
    a = a / np.linalg.norm(a)
    b = b / np.linalg.norm(b)

    # 利用空间圆的参数方程生成圆
    c1 = center[0] * np.ones((sample_num, 1))
    c2 = center[1] * np.ones((sample_num, 1))
    c3 = center[2] * np.ones((sample_num, 1))

    [c_x, c_y, c_z] = c1 + r*a[0]*np.cos(sample) + r*b[0]*np.sin(sample),\
                      c2 + r*a[1]*np.cos(sample) + r*b[1]*np.sin(sample),\
                      c3 + r*a[2]*np.cos(sample) + r*b[2]*np.sin(sample)

    # 加噪声
    nos1 = 0.2 * np.random.normal(1.3, noise, sample_num)
    nos2 = 0.2 * np.random.normal(1.1, noise, sample_num)
    nos3 = 0.2 * np.random.normal(1.1, noise, sample_num)
    c_y += nos1
    c_x += nos2
    c_z += nos3

    return c_x, c_y, c_z


# 散点生成
x=[]

x.append(generate_3D_circle(center=[2, 2, 0], n = [-1, 1, 0]))
x.append(generate_3D_circle(center=[-2, 2, 0], n = [1, 1, 0]))
x.append(generate_3D_circle(center=[2, -2, 0], n = [1, 1, 0]))
x.append(generate_3D_circle(center=[-2, -2, 0], n = [-1, 1, 0]))
x.append(generate_3D_circle(center=[0, 0, 0], n = [0, 0, 1]))


# 绘制散点图
fig = plt.figure()
ax = Axes3D(fig)
for i in x:
    ax.scatter(i[0], i[1], i[2])


# X, Y, Z = [], [], []
# for i in x:
#     X.append(i[0])
#     Y.append(i[1])
#     Z.append(i[2])
# ax.scatter(X, Y, Z)
plt.show()

参考

http://blog.sina.com.cn/s/blog_6496e38e0102vi7e.html

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值