如何在Matplotlib中指定位置绘制3D坐标系?
实现Matplotlib 3D坐标系从公共原点出发的效果
你想要把Matplotlib默认的3D坐标轴(如图1所示,贴在空间边缘)改成从公共原点出发的样式(如图2所示),这个需求其实只需要几行简单的代码设置就能实现。
效果对比
图1:Matplotlib默认坐标系绘制效果

图2:预期的坐标系绘制位置

关键修改步骤
在你设置坐标轴标签的代码块之后,添加以下三行配置:
# 调整坐标轴,让它们从公共原点出发 ax.xaxis._axinfo['juggled'] = (0, 0, 0) ax.yaxis._axinfo['juggled'] = (1, 1, 1) ax.zaxis._axinfo['juggled'] = (2, 2, 2)
修改后的完整代码
import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D def plot_3Dcube(): """Plots a 3D cube in a 3D-window """ #-------------------------------------- # PROCESS ARGUMENTS AND LOCAL VARIABLES #-------------------------------------- mycube = cube() # The cube to be plotted #--------------- # Setup the plot #--------------- fig = plt.figure() ax = fig.add_subplot(111,projection="3d") #--------------------------------------------- # Format the point-data and add it to the plot #--------------------------------------------- colour = (1.0, 0, 0, 1) # RGB, alpha mrkr = '^' s = 50 print(mycube) ax.scatter(mycube[:,0], mycube[:,1], mycube[:,2], c=colour, marker=mrkr) ptnr = 0 for row in mycube: ptnr += 1 ax.text(row[0], row[1], row[2], str(ptnr), size=8, color=(0,0,0)) #---------------- # Format the plot #---------------- ax.set_xlabel('X as') ax.set_ylabel('Y as') ax.set_zlabel('Z as') # 新增:调整坐标轴到公共原点 ax.xaxis._axinfo['juggled'] = (0, 0, 0) ax.yaxis._axinfo['juggled'] = (1, 1, 1) ax.zaxis._axinfo['juggled'] = (2, 2, 2) #-------------- # SHOW THE PLOT #-------------- ax.view_init(15, 30) plt.show() return None def cube(): """Returns the eight points of a cube in a numpy-array. """ c = np.array([[5.0, 0.0, 5.0], # Ptnr 1, Front UpperLeft [5.0, 5.0, 5.0], # Ptnr 2, Front Upper Right [5.0, 5.0, 0.0], # Ptnr 3, Front Lower Right [5.0, 0.0, 0.0], # Ptnr 4, Front Lower Left [0.0, 0.0, 5.0], # Ptnr 5, Back, Upper Right [0.0, 5.0, 5.0], # Ptnr 6, Back, Upper Left [0.0, 5.0, 0.0], # Ptnr 7, Back, Lower Left [0.0, 0.0, 0.0], # Ptnr 8, Back, Lower Right ]) return c #================================================================== # TEST area #================================================================== def main(): print("Entering Main()\n") plot_3Dcube() if __name__ == "__main__": main()
原理说明
juggled是Matplotlib 3D轴对象的内部配置参数,它的三元组分别控制:
- 第一个值:轴的延伸方向
- 第二个值:轴刻度的显示位置
- 第三个值:轴标签的放置位置
默认配置会让坐标轴贴在绘图区域的边缘,而我们将其设置为(轴索引, 轴索引, 轴索引)时,就会强制坐标轴从原点(0,0,0)位置出发,形成你想要的公共原点效果。
如果想要让原点坐标轴更突出,还可以添加ax.grid(False)来关闭默认网格。
内容的提问来源于stack exchange,提问作者PeterDev




