提问人:Etienne 提问时间:11/8/2023 最后编辑:Trenton McKinneyEtienne 更新时间:11/10/2023 访问量:50
如何为两个对齐的子图之间的空间着色
How to color the space between two aligned subplots
问:
我正在 matplotlib 中创建一个图形,其中三个子图水平对齐。 三个子图具有不同的背景颜色。 我想要的是子图之间的空间与右侧的子图颜色相同。 我试图在图中插入一个补丁并将这个补丁的坐标固定在子图坐标中,但没有成功。
我尝试了以下代码
import matplotlib.pyplot as mplt
import matplotlib.patches as patches
fig1, (ax1, ax2) = mplt.subplots(1,2)
# set graph dimension
ax1.set_xlim([1150,1200])
ax1.set_ylim([-210, 10])
ax2.set_xlim([2350,2400])
ax2.set_ylim([-210, 10])
# Set the axis labels position and content
x_yLabel, y_yLabel= 0.01, 0.95
x_xLabel, y_xLabel = 0.99, 0.05
# Define the shaded region along the x-axis
x_start1 = 1150
x_end1 = 1200
x_start2 = 2300
x_end2 = 2400
#Define colors for CO and Ar
shade_colorAr = 'mediumseagreen'
shade_colorCO = 'indianred'
# Draw the plain background
# For the first Ar flush
ax1.axvspan(x_start1, x_end1, facecolor=shade_colorAr, alpha=0.8)
# For the CO flush
ax2.axvspan(x_start2, x_end2, facecolor=shade_colorCO, alpha=0.8)
x_fig1, y_fig1 = ax1.transFigure.transform((1200, -210))
x_fig2, y_fig2 = ax2.transFigure.transform((2350, 10))
# Define the coordinates for the rectangle
rect = patches.Rectangle((x_fig1, y_fig1), x_fig2-x_fig1, y_fig2-y_fig1, linewidth=1, edgecolor='none', facecolor='lightblue',zorder=1)
# Add the rectangle to the figure
fig1.patches.append(rect)
我不得不承认这是 ChatGPT 的建议,但由于以下错误而不起作用:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Cell In[4], line 30
26 # For the CO flush
27 ax2.axvspan(x_start2, x_end2, facecolor=shade_colorCO, alpha=0.8)
---> 30 x_fig1, y_fig1 = ax1.transFigure.transform((1200, -210))
31 x_fig2, y_fig2 = ax2.transFigure.transform((2350, 10))
33 # Define the coordinates for the rectangle
AttributeError: 'Axes' object has no attribute 'transFigure'
答:
1赞
tmdavison
11/8/2023
#1
一种选择是设置 的变换 ,并在图形坐标中定义所有内容。Rectangle
fig.transFigure
当我们将补丁添加到 时,但它需要延伸到该轴之外,我们还需要设置它,使其不会被剪裁。ax1
clip_on=False
注意:在我看来,这是比将补丁添加到图形实例更好的选择,因为这样默认情况下它会在轴的前面,或者如果您将 zorder 设置在轴下方,您将不再在轴限制内看到补丁。
例如:
import matplotlib.pyplot as plt
import matplotlib.patches as patches
fig, (ax1, ax2) = plt.subplots(ncols=2)
# ax.get_position() returns a BBox in figure coordinates
x0 = ax1.get_position().x0 # left of ax1
x1 = ax2.get_position().x0 # left of ax2
y0 = ax1.get_position().y0 # bottom of ax1
y1 = ax1.get_position().y1 # top of ax1
w = x1 - x0 # width of rectangle is distance from left of ax1 to left of ax2
h = y1 - y0 # height of rectangle is height of Axes
# Create rectangle. set transform to figure transform, and set
# clip_on=False so it can extend outside of ax1 limits
rect = patches.Rectangle((x0, y0), w, h, facecolor='r',
clip_on=False, transform=fig.transFigure)
# add rectangle to ax1
ax1.add_patch(rect)
plt.show()
评论
ax1.figure.transFigure