首页 > 解决方案 > 使用 matplotlib 3D 在左右轴上绘图

问题描述

我是使用 Matplotlib 的新手,我有一些问题。

这是第一个案例:[1]:https ://i.stack.imgur.com/ra1no.png [2]:https ://i.stack.imgur.com/iQSrq.png

改变方位角 90 度时,有什么方法可以改变轴上显示的标签?我想要的是,与其在另一边拥有相同的标签,我更愿意成为 West。

我的另一个问题是,是否有办法防止图表出现负高度?

[3] https://i.stack.imgur.com/B493F.png

这是代码

import numpy as np
from mpl_toolkits.mplot3d.art3d import Poly3DCollection, Line3DCollection
import matplotlib.pyplot as plt
points = np.array([[-1, -1, -1],
                  [1, -1, -1 ],
                  [1, 1, -1],
                  [-1, 1, -1],
                  [-1, -1, 1],
                  [1, -1, 1 ],
                  [1, 1, 1],
                  [-1, 1, 1]])
Z = points
Z = 10.0*Z
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

r = [-1,1]
X, Y = np.meshgrid(r, r)
ax.scatter3D(Z[:, 0], Z[:, 1], Z[:, 2])
verts = [[Z[0],Z[1],Z[2],Z[3]],
 [Z[4],Z[5],Z[6],Z[7]],
 [Z[0],Z[1],Z[5],Z[4]],
 [Z[2],Z[3],Z[7],Z[6]],
 [Z[1],Z[2],Z[6],Z[5]],
 [Z[4],Z[7],Z[3],Z[0]]]
ax.add_collection3d(Poly3DCollection(verts, facecolors='cyan', linewidths=1, edgecolors='r', alpha=.20))
ax.set_xlabel('South', fontweight ='bold')
ax.set_ylabel('East')
#ax.set_zlabel('Z')
plt.show()

谢谢你。

标签: pythonmatplotlib

解决方案


我们可以使用事件处理来做到这一点。

对于您的第一个问题(设置“东”或“西”标签),我们可以在出现平局事件时捕捉并相应地定义我们ylabel

对于第二个问题(停止高程变为负数),我们可以确保高程仅限于正数。

示例函数如下所示。plt.show()在你的脚本之前添加这个:

def draw_func(event):
    # Change label to East or West depending on azimuth
    if ax.azim > 90 or ax.azim < -90:
        ax.set_ylabel('West')
    else:
        ax.set_ylabel('East')

    # don't let elevation go negative
    if ax.elev < 1:
        ax.view_init(elev=max(ax.elev, 1), azim=ax.azim)

fig.canvas.mpl_connect('draw_event', draw_func)

在此处输入图像描述

我在这个解决方案中看到的唯一问题是它允许视图高度变为负值并且快速恢复为正值。这对您来说可能就足够了;如果没有,其他人可能知道更好的解决方案


推荐阅读