matplotlib 在三维中旋转轴标签文本

n3schb8v  于 2023-06-23  发布在  其他
关注(0)|答案(1)|浏览(217)

如何旋转z标签,使文本显示为(bottom => top),而不是(top => bottom)?

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

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.set_zlabel('label text flipped', rotation=90) 
ax.azim = 225
plt.show()

无论我的ax.azim设置是什么,我都希望它保持不变。这似乎是一个old feature request on github,但没有在它的工作。是否有变通方案?

k5hmc34c

k5hmc34c1#

作为解决方法,您可以通过以下方式手动设置z标签的方向:

ax.zaxis.set_rotate_label(False)  # disable automatic rotation
ax.set_zlabel('label text', rotation=90)

请注意,z标签的方向也取决于您的视点,例如:

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

fg = plt.figure(1); fg.clf()
axx = [fg.add_subplot(4,1,1+i, projection='3d') for i in range(4)]
for ax,azel in zip(axx, [(115,10), (115,-10), (-115,10), (-115,-10)]):
    ax.set_title(u"Azim, elev = {}°, {}°".format(*azel))
    ax.set_zlabel('label text')
    ax.azim, ax.elev = azel

fg.canvas.draw()
plt.show()

给出

**更新:**也可以调整已绘制(但不是预先绘制)的图的z标签方向。这是修改标签的调整版本:

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

fg = plt.figure(1); fg.clf()
axx = [fg.add_subplot(4,1,1+i, projection='3d') for i in range(4)]
for ax,azel in zip(axx, [(115,10), (115,-10), (-115,10), (-115,-10)]):
    ax.set_title(u"Azim, elev = {}°, {}°".format(*azel))
    ax.set_zlabel('label text')
    ax.azim, ax.elev = azel
fg.canvas.draw()  # the angles of the text are calculated here

# Read drawn z-label rotations and switch them if needed
for ax in axx:
   ax.zaxis.set_rotate_label(False)
   a = ax.zaxis.label.get_rotation()
   if a<180:
       a += 180
   ax.zaxis.label.set_rotation(a)
   a = ax.zaxis.label.get_rotation() # put the actual angle in the z-label
   ax.set_zlabel(u'z-rot = {:.1f}°'.format(a))
fg.canvas.draw()

plt.show()

相关问题