Matplotlib: Subplot Background (axes Face + Labels) Colour [or, Figure/axes Coordinate Systems]
I have a figure containing 3x2 subplots, and I would like to set a background colour on the middle pair of subplots to make it clearer which axis labels belong to which subplot. Se
Solution 1:
Just use the transform
kwarg to Rectangle
, and you can use any coordinate system you'd like.
As a simple example:
import matplotlib.pyplotas plt
from matplotlib.patchesimportRectangle
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()
However, if you wanted to do things more robustly, and calculate the extent of the axes, you might do something like this:
import matplotlib.pyplot as plt
from matplotlib.transforms import Bbox
from matplotlib.patches import Rectangle
deffull_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()
Post a Comment for "Matplotlib: Subplot Background (axes Face + Labels) Colour [or, Figure/axes Coordinate Systems]"