我有一个包含3x2子图的图形,我想在中间的一对子图上设置背景颜色,以便更清楚哪些轴标签属于哪个子图。
在构建子图时设置facecolor
仅更改轴定义的区域的颜色;刻度线和轴标签仍然在figure.patch
上绘制。假设没有简单的方法可以做到这一点,我可以在figure.axes
中的相关实例后面添加一个矩形补丁。
经过一些实验后,似乎figure.axes[x].get_position()
返回Axescoördinates(标准化coördinates[0.0-1.0]),但Rectangle()
似乎想要显示cocordinates(像素)。此代码或多或少有效(ED:交互式,但在输出到png时(使用Agg渲染器),Rectangle的定位完全关闭):
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] )
但似乎非常hackish,感觉我错过了重要的事情。任何人都可以解释一下,是否有更简单/更好的方法,如果是,它是什么?
由于我真的需要写一个文件,我现在没有解决方案。
答案 0 :(得分:6)
只需使用transform
kwarg Rectangle
即可,您可以使用任何您喜欢的坐标系。
举个简单的例子:
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()