问题描述
我有一个包含多个子图的复杂图形。我想在多个子图上绘制一个矩形,确保该矩形跨越其覆盖的子图的轴的整个高度。 SO here上也有类似的问题,但是要推断出不同大小的子图的情况并非易事。
采用以下示例代码:
import numpy as np
import matplotlib.pylab as plt
import matplotlib.patches as patches
# Generate figure with subplots
fig,ax = plt.subplots(nrows=2,ncols=1,gridspec_kw={'left':0.15,'right':0.97,'bottom':0.1,'top':0.97,'height_ratios': [2,0.9],'hspace': 0.05},figsize=(10,5))
# Some surrogate data
x = np.arange(0,2*np.pi,np.pi/50)
y1 = 10*np.cos(x)
y2 = np.sin(x)
ax[0].plot(x,y1)
ax[1].plot(x,y2)
# Now I would like to draw -- say -- two rectangles spanning the two plots in their height:
# -- one for pi/4<x<pi/2;
# -- another for pi<2/3*pi
# I am using patchCollections
rec_patches = []
left = [np.pi/4,np.pi]
width = [np.pi/4,np.pi/2]
for i in range(2):
######## HERE I AM STUCK ########
rec_patches.append(patches.Rectangle((left[i],??bottom??),width[i],??height??,lw=2))
# Add to axes
ax[1].add_collection(collections.PatchCollection(rec_patches,match_original=False))
我陷入了在Rectangle
循环中创建每个for
的行中。如何获得bottom
和height
,以便可以使矩形从x
的{{1}}轴开始并在{{1 }}?原则上,我可以通过ax[1]
获得有用的信息,但是我获得的ax[0]
是相对于ax[i].get_position()
的单位。另一方面,我以数据单位传递Bbox
和figure
。我可能应该使用某种转换,并且我知道left
有一个输入参数width
,但我不知道该怎么做以及这是否正确。请记住,我希望我的方法是可靠的,并且独立于要绘制的数据。图片勾勒出矩形跨越多个不同大小的子图的想法。另外,Rectangle
中的transform
仍然是一个棘手的话题,因为官方文档并不直接。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)