在3D散点图上绘制多组数据
我在把多个数据集画到一个3D散点图上时遇到了麻烦。我现在有三个方程,并且我用线性代数的方法计算这些方程的零点。然后,我把每组零点都画到一个3D图上。为了观察零点是如何变化的,我会改变其中一个参数的值。我的目标是把所有的数据集都放在一个3D散点图上,这样就能方便地比较它们之间的差异,但我每次都只能得到一个数据集的图。有没有人能帮我找出我需要修正的地方?
import numpy as np
from numpy import linalg
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
plt.close('all')
#Will be solving the following system of equations:
#sx-(b/r)z=0
#-x+ry+(s-b)z=0
#(1/r)x+y-z=0
r=50.0
b=17.0/4.0
s=[10.0,20.0,7.0,r/b]
color=['r','b','g','y']
markers=['s','o','^','d']
def system(s,b,r,color,m):
#first creates the matrix as an array so the parameters can be changed from outside
#and then coverts array into a matrix
u_arr=np.array([[s,0,-b/r],[-1,r,s-b],[1/r,1,-1]])
u_mat=np.matrix(u_arr)
U_mat=linalg.inv(u_mat)
#converts matrix into an array and then into a list to manipulate
x_zeros=np.array(U_mat[0]).reshape(-1).tolist()
y_zeros=np.array(U_mat[1]).reshape(-1).tolist()
z_zeros=np.array(U_mat[2]).reshape(-1).tolist()
zeros=[x_zeros,y_zeros,z_zeros]
coordinates=['x','y','z']
print('+'*70)
print('For s=%1.1f:' % s)
print('\n')
for i in range(3):
print('For the %s direction, the roots are: ' % coordinates[i])
for j in range(3):
print(zeros[i][j])
print('-'*50)
fig3d=plt.figure()
ax=Axes3D(fig3d)
ax.scatter(x_zeros,y_zeros,z_zeros,c=color,marker=m)
plt.title('Zeros for a Given System of Equations for s=%1.1f' % (s))
ax.set_xlabel('Zeros in x Direction')
ax.set_ylabel('Zeros in y Direction')
ax.set_zlabel('Zeros in z Direction')
plt.show()
for k in range(len(s)):
system(s[k],b,r,color[k],markers[k])
提前感谢大家的帮助。
1 个回答
2
每次调用 system()
时,你都在创建一个新的坐标轴实例。应该把 ax
作为参数传递给 system
。
def system(s,b,r,color,m, ax):
# ...
ax.scatter(x_zeros,y_zeros,z_zeros,c=color,marker=m)
然后在循环之前创建坐标轴实例。
fig3d=plt.figure()
ax=Axes3D(fig3d)
for k in range(len(s)):
system(s[k],b,r,color[k],markers[k], ax)
plt.show()
这样所有的图形都会添加到 ax
上。你可能还想考虑在 system()
函数外设置坐标轴的标签等。可以把这个过程分成两个函数,一个用来设置图形,另一个用来生成所需的数据并绘制它。