matplotlib: 子图背景(坐标轴面 + 标签)颜色【或,图形/坐标轴坐标系】

3 投票
1 回答
4658 浏览
提问于 2025-04-17 14:50

我有一个包含3行2列子图的图形,我想给中间那一对子图设置一个背景颜色,这样可以更清楚地显示每个坐标轴标签属于哪个子图。

在创建子图时设置facecolor只会改变坐标轴定义区域的颜色;而刻度和坐标轴标签还是会显示在figure.patch上。假设没有简单的方法可以做到这一点,我可以在figure.axes中相关的实例后面添加一个矩形补丁。

经过一番实验,我发现figure.axes[x].get_position()返回的是坐标轴的坐标(归一化坐标[0.0-1.0]),而Rectangle()似乎需要的是显示坐标(像素)。这段代码大致上是可行的(注意:在交互模式下可以用,但当输出为png文件时(使用Agg渲染器),矩形的位置完全不对):

import matplotlib.pyplot as plt
import matplotlib

f = plt.figure()
plt.subplot( 121 )
plt.title( 'model' )
plt.plot( range(5), range(5) )
plt.xlabel( 'x axis' )
plt.ylabel( 'left graph' )
plt.subplot( 122 )
plt.title( 'residuals' )
plt.plot( range(5), range(5) )
plt.xlabel( 'x axis' )
plt.ylabel( 'right graph' )
plt.tight_layout(pad=4)

bb = f.axes[0].get_position().transformed( f.transFigure ).get_points()
bb_pad = (bb[1] - bb[0])*[.20, .10]
bb_offs = bb_pad * [-.25, -.20]
r = matplotlib.patches.Rectangle( bb[0]-bb_pad+bb_offs, *(bb[1] - bb[0] + 2*bb_pad),
                                  zorder=-10, facecolor='0.85', edgecolor='none' )
f.patches.extend( [r] )

不过这看起来很像是个临时解决办法,我感觉自己错过了什么重要的东西。有没有人能解释一下,是否有更简单或更好的方法,如果有的话,那是什么呢?

因为我确实需要写入一个文件,目前我还没有找到解决方案。

1 个回答

7

只需要在Rectangle中使用transform这个参数,你就可以使用任何你想要的坐标系统。

举个简单的例子:

import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle

fig, axes = plt.subplots(3, 2)

rect = Rectangle((0.08, 0.35), 0.85, 0.28, facecolor='yellow', edgecolor='none',
                 transform=fig.transFigure, zorder=-1)
fig.patches.append(rect)
plt.show()

这里输入图片描述

不过,如果你想做得更稳妥一些,计算坐标轴的范围,你可以这样做:

import matplotlib.pyplot as plt
from matplotlib.transforms import Bbox
from matplotlib.patches import Rectangle

def full_extent(ax, pad=0.0):
    """Get the full extent of an axes, including axes labels, tick labels, and
    titles."""
    # For text objects, we need to draw the figure first, otherwise the extents
    # are undefined.
    ax.figure.canvas.draw()
    items = ax.get_xticklabels() + ax.get_yticklabels() 
#    items += [ax, ax.title, ax.xaxis.label, ax.yaxis.label]
    items += [ax, ax.title]
    bbox = Bbox.union([item.get_window_extent() for item in items])
    return bbox.expanded(1.0 + pad, 1.0 + pad)


fig, axes = plt.subplots(3,2)

extent = Bbox.union([full_extent(ax) for ax in axes[1,:]])

# It's best to transform this back into figure coordinates. Otherwise, it won't
# behave correctly when the size of the plot is changed.
extent = extent.transformed(fig.transFigure.inverted())

# We can now make the rectangle in figure coords using the "transform" kwarg.
rect = Rectangle([extent.xmin, extent.ymin], extent.width, extent.height,
                 facecolor='yellow', edgecolor='none', zorder=-1, 
                 transform=fig.transFigure)
fig.patches.append(rect)

plt.show()

这里输入图片描述

撰写回答