GridSpec 和 ConnectionPatch 问题

时间:2020-12-31 07:43:34

标签: python matplotlib subplot arrows

我正在尝试绘制一个大图,然后使用箭头将异常值连接到较小的图。我使用 gridspec 来创建我的绘图,并且它们本身显示完美。

但是,当我尝试使用 ConnectionPatch 为箭头添加艺术家时,它会更改所有子图的大小。

这是我使用 gridspec 设置图形和子图的代码:

fig2 = plt.figure(constrained_layout=True)
gs = fig2.add_gridspec(ncols=3, nrows=9, figure=fig2)

f2_ax1 = fig2.add_subplot(gs[0:-4, :-1])

f2_ax2 = fig2.add_subplot(gs[2:-4, 2])


f2_ax3 = fig2.add_subplot(gs[5:-1, 0])


f2_ax4 = fig2.add_subplot(gs[5:-1, 1])


f2_ax5 = fig2.add_subplot(gs[5:-1,2])

这会创建我想要的图(见图):

enter image description here

这是我如何向图中添加箭头,使用 for 循环遍历每个子图:

coordsA = "data" #The arrows are plotting using the same coordinates as the data points
coordsB = "data"
i = 0
for sub_plot in sub_plot_list: #Adding the arrows to the subplots
    xy1 = (x_oulier_list[i], y_outlier_list[i]) #Fetches coordinates for beginning of arrow 
    xy2 = arrow_end_list[i] #Fetches coordinates for the pointy end of arrow 
    con = ConnectionPatch(xyA=(x_outlier_list[i],y_outlier_list[i]), xyB=arrow_end_list[i], 
                          coordsA=coordsA, coordsB=coordsB,
                          axesA=f2_ax1, axesB=sub_plot,
                          arrowstyle="->", shrinkB=5)

    f2_ax1.add_artist(con) #Adds arrow to plot
    i += 1 

两个版本都使用 fig2.tight_layout()

这是添加箭头后的图:

enter image description here

知道如何修复它以便在添加箭头时绘图的尺寸不会改变吗?

1 个答案:

答案 0 :(得分:2)

问题似乎出在 constrained_layout 上,它似乎不能很好地处理 ConnectionPatchconstrained_layout 仍处于实验阶段,也许值得在 matplotlib 的 github 上提出问题以防万一有人可以解决问题)。

一个简单的解决方法是请求使用以下方法计算布局时考虑 ConnectionPatch 对象:

(...)
    con = ConnectionPatch(xyA=(x_outlier_list[i],y_outlier_list[i]), xyB=arrow_end_list[i], 
                          coordsA=coordsA, coordsB=coordsB,
                          axesA=f2_ax1, axesB=sub_plot,
                          arrowstyle="->", shrinkB=5)
    con.set_in_layout(False)
(...)
相关问题