3

3x2 サブプロットを含む図があり、サブプロットの中央のペアに背景色を設定して、どの軸ラベルがどのサブプロットに属しているかを明確にしたいと考えています。

サブプロットを作成するときの設定facecolorは、軸によって定義された領域の色のみを変更します。目盛りと軸のラベルは引き続き に描画されfigure.patchます。これを行う簡単な方法がないと仮定すると、 の関連するインスタンスの背後に長方形のパッチを追加できますfigure.axes

少し実験した後、figure.axes[x].get_position()Axes 座標 (正規化された座標 [0.0-1.0]) を返すように見えますが、 Rectangle()Display 座標 (ピクセル) が必要なようです。このコードは多かれ少なかれ機能します (ED: インタラクティブに、ただし (Agg レンダラーを使用して) PNG に出力する場合、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] )

しかし、非常にハックなようで、何か重要なことを見逃しているように感じます. それを行うためのより簡単な/より良い方法があるかどうか、そしてもしそうなら、それは何ですか?

私は本当にファイルに書き込む必要があるので、現在解決策がありません。

4

1 に答える 1

7

transformkwarg to を使用するだけ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()

ここに画像の説明を入力

于 2013-02-06T02:27:47.097 に答える