在 matplotlib 中优雅地改变绘图框的颜色

2023-12-19

这是一个后续问题this https://stackoverflow.com/questions/4761623/changing-the-color-of-the-axis-ticks-and-labels-for-a-plot-in-matplotlib帖子,其中讨论了轴、刻度和标签的颜色。我希望为此提出一个新的扩展问题是可以的。

更改双图周围完整框架(刻度线和轴)的颜色(通过add_subplot) 和轴 [ax1, ax2] 会产生大量代码。此片段更改框架的颜色上图的:

ax1.spines['bottom'].set_color('green')
ax1.spines['top'].set_color('green')
ax1.spines['left'].set_color('green')
ax1.spines['right'].set_color('green')
for t in ax1.xaxis.get_ticklines(): t.set_color('green')
for t in ax1.yaxis.get_ticklines(): t.set_color('green')
for t in ax2.xaxis.get_ticklines(): t.set_color('green')
for t in ax2.yaxis.get_ticklines(): t.set_color('green')

因此,为了更改两个图的框架颜色,每个图有两个 y 轴,我需要 16(!) 行代码...它是这样的:

到目前为止我发现的其他方法:

  • matplotlib.rc:讨论here https://stackoverflow.com/questions/1982770/matplotlib-changing-the-color-of-an-axis;改变是全球性的,而不是局部性的。我想要一些不同颜色的其他图。请不要讨论图中过多的颜色......:-)

    matplotlib.rc('axes',edgecolor='green')
    
  • 挖出轴的刺,然后改变它:也讨论过here https://stackoverflow.com/questions/1982770/matplotlib-changing-the-color-of-an-axis;我认为不太优雅。

    for child in ax.get_children():
        if isinstance(child, matplotlib.spines.Spine):
            child.set_color('#dddddd')
    

有没有一个elegant压缩上述块的方法,一些东西 更“Pythonic”?

我在 ubuntu 下使用 python 2.6.5 和 matplotlib 0.99.1.1 。


假设您使用的是相当最新的 matplotlib 版本(>= 1.0),也许可以尝试这样的操作:

import matplotlib.pyplot as plt

# Make the plot...
fig, axes = plt.subplots(nrows=2)
axes[0].plot(range(10), 'r-')
axes[1].plot(range(10), 'bo-')

# Set the borders to a given color...
for ax in axes:
    ax.tick_params(color='green', labelcolor='green')
    for spine in ax.spines.values():
        spine.set_edgecolor('green')

plt.show()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 matplotlib 中优雅地改变绘图框的颜色 的相关文章

随机推荐