首页 > 解决方案 > 设置 matplotlib 3D 绘图的刻度颜色

问题描述

如果我有 3D matplotlib 图(Axes3D对象),如何更改刻度线的颜色?我想出了如何更改轴线、刻度标签和轴标签的颜色。显而易见的解决方案 useax.tick_params(axis='x', colors='red')只更改刻度标签而不是刻度线本身。

这是尝试将所有轴更改为红色并获取除刻度线之外的所有内容的代码:

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

fig = plt.figure()
ax = Axes3D(fig)

ax.scatter((0, 0, 1), (0, 1, 0), (1, 0, 0))
ax.w_xaxis.line.set_color('red')
ax.w_yaxis.line.set_color('red')
ax.w_zaxis.line.set_color('red')
ax.w_zaxis.line.set_color('red')
ax.xaxis.label.set_color('red')
ax.yaxis.label.set_color('red')
ax.zaxis.label.set_color('red')
ax.tick_params(axis='x', colors='red')  # only affects
ax.tick_params(axis='y', colors='red')  # tick labels
ax.tick_params(axis='z', colors='red')  # not tick marks

fig.show()

在此处输入图像描述

标签: pythonmatplotlibmplot3d

解决方案


手册页中所述,tick_params(axis='both', **kwargs)您会遇到错误:

虽然当前已实现此功能,但 Axes3D 对象的核心部分可能会忽略其中一些设置。未来的版本将解决此问题。提交错误的人将优先考虑。

要覆盖此问题,请使用内部_axinfo字典,如本例所示

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

fig = plt.figure()
ax = fig.gca(projection='3d')

ax.scatter((0, 0, 1), (0, 1, 0), (1, 0, 0))

ax.xaxis._axinfo['tick']['color']='r'
ax.yaxis._axinfo['tick']['color']='r'
ax.zaxis._axinfo['tick']['color']='r'
plt.show()

在此处输入图像描述


推荐阅读