更改坐标轴颜色

120 投票
4 回答
172352 浏览
提问于 2025-04-15 17:29

有没有办法在matplotlib中改变坐标轴的颜色(不是刻度线的颜色)?我查阅了Axes、Axis和Artist的文档,但没有找到相关信息;matplotlib的图库里也没有提示。有没有什么想法?

4 个回答

23

为了记录一下,这是我让它工作的方式:

fig = pylab.figure()
ax  = fig.add_subplot(1, 1, 1)
for child in ax.get_children():
    if isinstance(child, matplotlib.spines.Spine):
        child.set_color('#dddddd')
26

你可以通过调整默认的rc设置来实现这个。

import matplotlib
from matplotlib import pyplot as plt

matplotlib.rc('axes',edgecolor='r')
plt.plot([0, 1], [0, 1])
plt.savefig('test.png')
229

在使用图形的时候,你可以很简单地改变边框的颜色,方法是:

ax.spines['bottom'].set_color('#dddddd')
ax.spines['top'].set_color('#dddddd') 
ax.spines['right'].set_color('red')
ax.spines['left'].set_color('red')

如果你只想改变刻度线的颜色,可以使用以下方法:

  • which="both" 这个选项会同时改变主要和次要刻度线的颜色
ax.tick_params(axis='x', colors='red')
ax.tick_params(axis='y', colors='red')

接下来,如果你只想改变标签的颜色,可以用:

ax.yaxis.label.set_color('red')
ax.xaxis.label.set_color('red')

最后,如果你想改变标题的颜色,可以使用:

ax.title.set_color('red')

撰写回答