matplotlib 如何为两个对齐的子图之间的空间着色

apeeds0o  于 2023-11-22  发布在  其他
关注(0)|答案(1)|浏览(132)

我在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'


的数据

wz3gfoph

wz3gfoph1#

一个选项是将Rectangle的变换设置为fig.transFigure,并在图形坐标中定义所有内容。
当我们将补丁添加到ax1时,但它需要扩展到该Axes之外,我们还需要设置clip_on=False,以便它不会被裁剪。
注意事项:在我看来,这是比将补丁添加到图示例更好的选择,因为默认情况下它将位于Axes之前,或者如果您将zorder设置为Axes以下,您将不再看到Axes限制内的补丁。
举例来说:

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()

字符串


的数据

相关问题