matplotlib scatter plot with xyz axis lines through origin (0,0,0) and axis project lines to each point

邮差的信 提交于 2021-02-11 07:14:38

问题


I always have this problem when plotting with matplotlib... they have no concept of drawing the axis lines on the plot, in this case, I specifically want xyz axis lines drawn on a scatter plot so that it looks like the attached photo, including the project lines from the point back to the axis.

ploting a point with explicit axis lines through origin

instead this is what i get:

# from jupyter notebook
%matplotlib
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()

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

ax.scatter( 1,  1,  1, c='r', marker='o')
ax.scatter( 1, -1,  1, c='b', marker='o')
ax.scatter(-1,  1, -1, c='g', marker='o')

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

ax.set_xlim(-2,2)
ax.set_ylim(-2,2)
ax.set_zlim(-2,2)

#ax.set_xticks(np.arange(-2, 2, 1))
#ax.set_yticks(np.arange(-2, 2, 1))
#ax.set_zticks(np.arange(-2, 2, 1))

plt.show()

回答1:


Ok, so maybe there is a direct way of achieving this. If not, this code will solve the greatest part of your problem. I created a function which generates the dashed lines as needed. Use ax.quiver() to generate the coordinate system.

EDIT: You can use commands like ax.set_axis_off()to generate the image you posted.

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

def make_dashedLines(x,y,z,ax):
    for i in range(0, len(x)):
        x_val, y_val, z_val = x[i],y[i],z[i]
        ax.plot([0,x_val],[y_val,y_val],zs=[0,0], linestyle="dashed",color="black")
        ax.plot([x_val,x_val],[0,y_val],zs=[0,0], linestyle="dashed",color="black")
        ax.plot([x_val,x_val],[y_val,y_val],zs=[0,z_val], linestyle="dashed",color="black")

fig = plt.figure()

ax = fig.add_subplot(111, projection='3d')
x = [1,1,-1]
y = [1,-1,1]
z = [1,1,-1]

ax.scatter( x,y,z, c='r', marker='o')
make_dashedLines(x,y,z,ax)

# Make a 3D quiver plot
x, y, z = np.array([[-2,0,0],[0,-2,0],[0,0,-2]])
u, v, w = np.array([[4,0,0],[0,4,0],[0,0,4]])
ax.quiver(x,y,z,u,v,w,arrow_length_ratio=0.1, color="black")
ax.grid(False)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')

ax.set_xlim(-2,2)
ax.set_ylim(-2,2)
ax.set_zlim(-2,2)

plt.show()

Output:



来源:https://stackoverflow.com/questions/54970401/matplotlib-scatter-plot-with-xyz-axis-lines-through-origin-0-0-0-and-axis-proj

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!