更改轴的颜色

120
有没有办法在matplotlib中更改轴(而不是刻度)的颜色?我已经查看了Axes、Axis和Artist的文档,但没有找到;matplotlib画廊也没有任何提示。有什么想法吗?
4个回答

226

使用图形时,您可以轻松地使用以下命令更改图形的脊柱颜色:

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')

3
ax.tick_params(axis='x', colors='red') 似乎会改变刻度线和标签的颜色... - Jonathan
是否可以以这样的方式使用 ax.yaxis.label.set_color('grey'),只更改从 y1y2 的刻度线颜色,而其他刻度线保持不变? - FaCoffee
有没有想法如何改变要散布的点的颜色? - Harit Vishwakarma
1
@FaCoffee 你可以通过调用 set_ticklabels() 并传递 kwarg color 来独立设置刻度标签的颜色,而不影响刻度线的颜色。像这样:ax.xaxis.set_ticklabels([0.0,0.2,0.4,0.6,0.8,1.0], color = 'k') - marisano
@Jonathan的评论对我很有用。关键是要使用colors参数,而不是color参数(请注意s)。 - Sia
请注意,我发现使用 plt.style.use('dark_background') 可以帮助在运行时进行此类操作。 - wellplayed

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')

3
Matplotlib也有一个上下文管理器,它允许暂时更改rc参数。http://stackoverflow.com/a/41527038/2166823 - joelostblom
1
感谢@joelostblom。我在浏览器和Jupyter笔记本上使用了深色背景。只需要一行代码就可以完成整个工作。从上下文的文档中可以看到:import matplotlib.pyplot as plt plt.style.use('dark_background') - Diego Mello

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')

我可以问一下为什么这个答案在顶部吗?它不是得票最多或被接受的解决方案。 - Tom

4
设置所有轴的边缘颜色全局通用:
matplotlib.rcParams['axes.edgecolor'] = '#ff0000'

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接