【问题标题】:Can you fit arrows automatically to a plt text in python?你能自动将箭头适合python中的plt文本吗?
【发布时间】:2020-09-11 23:14:14
【问题描述】:

我有一些矩形,其中包含由有向边连接的文本,我的代码如下:


import matplotlib.pyplot as plt



plt.close()   

pos_rec={0: (0,0), 1:(20,30), 2:(50,10)}

text_rec={0:"ShortText", 1:"A Bit Longer", 2:"A Much Longer Text" }

ax = plt.gca()

edges=((0,1),(1,2),(2,0))


for i in pos_rec:
        plt.text(pos_rec[i][0],pos_rec[i][1],s=text_rec[i],fontsize=15,fontweight="bold", bbox=dict(boxstyle='round',facecolor='red', edgecolor='r', pad=0.7),horizontalalignment='center')


for edge in edges:
    ax.annotate("",xy=pos_rec[edge[0]], xytext=pos_rec[edge[1]],
    arrowprops=dict(arrowstyle="<|-,head_length=1,head_width=0.5",lw=2, shrinkA=18, shrinkB=20, color='b')
    )
    


 
plt.show()

现在的问题是边缘卡在盒子里,这当然看起来不是很漂亮 - 我可以通过在边缘之后绘制盒子来解决这个问题,所以重叠被盒子隐藏了但是边缘箭头可能消失;

使用选项 shrinkA 和 shrinkB 我可以调整起点和终点的箭头长度,因此理论上我可以手动修复它,使箭头确实在矩形处结束。问题是这些箭头卡在盒子中的深度不同 - 此外,根据我选择的比例,箭头可能在这些盒子内更深或更浅;

不同尺度的代码输出可见这里:

所以对我来说很自然的问题是:是否有可能让这些边缘直接在这些矩形的边界处结束?

这是否可以独立于缩放来完成,即无论我放大还是缩小,边缘总是在矩形的边界处结束?

如果这些边缘是弯曲的,如下例所示?

【问题讨论】:

    标签: python matplotlib networkx


    【解决方案1】:

    您可以使用get_tighbbox()获取边界框,并根据.bounds绘制箭头。还建议您阅读 matplotlib 的 transformations tutorial 了解更多信息。

    fig, ax = plt.subplots(1, 1, figsize=(7.2, 7.2))
    ax.set_xlim(0, 1)
    ax.set_ylim(0, 1)
    
    t1 = ax.text(0.5, 0.5, 'text',  bbox=dict(boxstyle='round',facecolor='red', edgecolor='r'))
    t2 = ax.text(0.3, 0.3, 'text',  bbox=dict(boxstyle='round',facecolor='red', edgecolor='r'))
    
    
    x1, y1, w1, h1 = t1.get_tightbbox(fig.canvas.get_renderer()).bounds
    x2, y2, w2, h2 = t2.get_tightbbox(fig.canvas.get_renderer()).bounds
    plt.annotate(' ', (x2+w2, y2+h2),(x1, y1), xycoords='figure pixels', arrowprops=dict(arrowstyle="<|-,head_length=1,head_width=0.5",lw=2, color='b'))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-23
      • 2018-12-14
      相关资源
      最近更新 更多