adjustText解决matplotlib plt.text()文字重叠问题

adjustText解决matplotlib plt.text()文字重叠问题

1.引言

我们在使用plt.text()绘制文本时,经常会出现文本内容重叠的问题,导致绘制的图非常难看,如果手动调整文本的文字复杂不现实,使用起来非常麻烦。但是,我们使用的是Python,这可是号称除了生小孩其它事儿都能做到的Python,丰富强大的封装库函数使得python成为了当今最受欢迎的编程语言之一,解决文字重叠这种小问题自然也不在话下,python的adjustText库就能完美解决这个问题,左边为未调整的,右边为调整过后的图片

image-20210324213203003image-20210324213254606

​ AdjustText是一个小型库,可帮助您调整matplotlib图上的文本位置,以消除或最小化彼此之间和数据点之间的重叠。该方法基于边界框的重叠,并迭代移动它们以减少重叠。这个想法来自R / ggplot2的ggrepel软件包(https://github.com/slowkow/ggrepel)。可以在以下位置找到带有问题跟踪器的存储库:https://github.com/Phlya/adjustText/。通过算法迭代可以轻松解决文本重合问题:

pic

​ 关于安装:

pip install adjustText
or 
conda install -c conda-forge adjusttext

2 adjustText使用方法

常用的参数含义

  • texts:List型,每个元素都是表示单个文字标签对应的matplotlib.text.Text对象

  • ax:绘制文字标签的目标axe对象,默认为最近一次的axe对象

  • lim:int型,控制迭代调整文本标签位置的次数,默认为500次

  • precision:float型,用于决定迭代停止的精度,默认为0.01,即所有标签相互遮挡部分的长和宽占所有标签自身长宽之和的比例,addjust_text会在精度达到precision和迭代次数超过lim这两个条件中至少有一个满足时停止迭代

  • only_move:字典型,用于指定文本标签与不同对象发生遮挡时的位移策略,键有'points''text''objects',对应的值可选'xy''x''y',分别代表竖直和水平方向均调整、只调整水平方向以及只调整竖直方向

  • arrowprops:字典型,用于设置偏移后的文字标签与原始位置之间的连线样式,下文会作具体演示

  • save_steps:bool型,用于决定是否保存记录迭代过程中各轮的帧图像,默认为False

  • save_prefix:str型,当save_steps设置为True时,用于指定中间帧保存的路径,默认为’’,即当前工作路径

    import matplotlib.pyplot as plt
    from adjustText import adjust_text
    import numpy as np
    import pandas as pd
    
    np.random.seed(0)
    x, y = np.random.random((2,30))
    fig, ax = plt.subplots()
    plt.plot(x, y, 'bo')
    texts = [plt.text(x[i], y[i], 'Text%s' %i) for i in range(len(x))]
    
    image-20210324213203003
    #------调整文字位置---------#
    adjust_text(texts,)
    
    image-20210324213254606
    adjust_text(texts, 
                arrowprops=dict(
        			arrowstyle='->',#箭头样式 
        			lw= 1,#线宽
        			color='red')#箭头颜色
               )
    
    _images/Examples_6_1.png

    除此之外,adjustText还可以对Label 对象文字位置进行调整

    import matplotlib.pyplot as plt
    from adjustText import adjust_text
    import numpy as np
    import pandas as pd
    
    data = [{'rf': [[10, 0.682312925170068], [20, 0.714904143475572], [30, 0.729107400535972], [40, 0.718944547515976], [50, 0.7372706658420943], [60, 0.7291486291486291], [70, 0.7332302618016904], [80, 0.7291486291486291], [90, 0.7291486291486291]], 'besttree': 0.7372706658420943}, {'rf': [[10, 0.6576994434137291], [20, 0.6760874046588332], [30, 0.7086786229643371], [40, 0.6943929086786229], [50, 0.6984951556380127], [60, 0.6903731189445474], [70, 0.7025974025974027], [80, 0.7128014842300556], [90, 0.7086786229643373]], 'besttree': 0.7128014842300556}, {'rf': [[10, 0.5763347763347764], [20, 0.5783962069676354], [30, 0.5946402803545661], [40, 0.5988455988455988], [50, 0.6028653885796743], [60, 0.6089466089466089], [70, 0.6171098742527313], [80, 0.6130488559059988], [90, 0.6130488559059988]], 'besttree': 0.6171098742527313}, {'rf': [[10, 0.6741084312512883], [20, 0.7025767882910741], [30, 0.6964337250051535], [40, 0.7127396413110699], [50, 0.7167594310451453], [60, 0.712677798392084], [70, 0.7269635126777982], [80, 0.7351061636775922], [90, 0.7350855493712636]], 'besttree': 0.7351061636775922}, {'rf': [[10, 0.6719645433931148], [20, 0.7006184291898577], [30, 0.7066378066378066], [40, 0.7107606679035251], [50, 0.7086580086580087], [60, 0.7269841269841271], [70, 0.718841475984333], [80, 0.7249433106575964], [90, 0.7188827045969903]], 'besttree': 0.7269841269841271}, {'rf': [[10, 0.5722119150690579], [20, 0.5641723356009071], [30, 0.5845186559472274], [40, 0.5947227375798805], [50, 0.6048649762935477], [60, 0.6049062049062048], [70, 0.6048443619872191], [80, 0.6007833436404865], [90, 0.6048855905998763]], 'besttree': 0.6049062049062048}, {'rf': [[10, 0.54582560296846], [20, 0.5478664192949907], [30, 0.5499278499278499], [40, 0.564172335600907], [50, 0.5621109049680477], [60, 0.5621109049680478], [70, 0.5600700886415172], [80, 0.5580705009276438], [90, 0.5600907029478458]], 'besttree': 0.564172335600907}, {'rf': [[10, 0.6171304885590599], [20, 0.6435992578849722], [30, 0.6354566068851784], [40, 0.6577819006390435], [50, 0.6618429189857762], [60, 0.6557410843125129], [70, 0.6638425066996495], [80, 0.65578231292517], [90, 0.6618841475984334]], 'besttree': 0.6638425066996495}, {'rf': [[10, 0.6578643578643579], [20, 0.6944135229849515], [30, 0.69853638425067], [40, 0.7005565862708719], [50, 0.6985569985569986], [60, 0.6985363842506699], [70, 0.6964955679241392], [80, 0.6923933209647496], [90, 0.7005565862708719]], 'besttree': 0.7005565862708719}]
    
    fig = plt.figure(facecolor="w",figsize=(15,15))
    for i,result in enumerate(data):
    # Let's plot the bars
        ax=fig.add_subplot(3,3,i+1)
        x = [item[0] for item in result['rf']]
        y = [item[1] for item in result['rf']]
        ax.axis(ymin=0.5,ymax=0.8,xmin=4,xmax=100)
        bars=ax.bar(x,y,color='green',tick_label=x,width=2)
    # And add the labels, while changing the colour of some of the bars
        texts=[]
        for j,rect in enumerate(bars):
            left = rect.get_x()+1
            top = rect.get_y()+rect.get_height()
            texts.append(ax.text(left,top,'%.3f'%y[j]))
            if y[j] == result['besttree']:
                rect.set_facecolor('red')
    
    
        ax.set_ylabel('CA')
        ax.set_title('%s iterations' % texts)
    

    image-20210324214042582

文字重叠惨不忍睹,对其进行调整:

   # Now adjust the text. We don't want to move in the x direction and we want the labels to vertically aligned with the bars.
# I also noticed that having a weaker force to repel texts from ech other makes the figure nicer.
    ax.set_title('%s iterations' % adjust_text(texts, add_objects=bars,
                 autoalign=False, only_move={'points':'y', 'text':'y', 'objects':'y'},
                 ha='center', va='bottom'))

更多的例子和使用方法请查看官网:https://adjusttext.readthedocs.io/en/latest/Examples.html

3.更多参数Module documentation

  • adjustText.``adjust_text(texts, x=None, y=None, add_objects=None, ax=None, expand_text=(1.05, 1.2), expand_points=(1.05, 1.2), expand_objects=(1.05, 1.2), expand_align=(1.05, 1.2), autoalign=‘xy’, va=‘center’, ha=‘center’, force_text=(0.1, 0.25), force_points=(0.2, 0.5), force_objects=(0.1, 0.25), lim=500, precision=0.01, only_move={‘objects’: ‘xy’, ‘points’: ‘xy’, ‘text’: ‘xy’}, avoid_text=True, avoid_points=True, avoid_self=True, save_steps=False, save_prefix=’’, save_format=‘png’, add_step_numbers=True, *args, **kwargs)[source]

    迭代地调整文本的位置。在完成所有绘制(尤其是可以更改轴限制的任何操作)之后,最后调用Adjust_text。这是因为要移动文本,该功能需要使用轴的尺寸,并且不知道绘图的最终大小,结果将是完全荒谬的或次佳的。首先,将所有超出轴限制的文本移入内部。
    然后,在每次迭代中,将所有文本彼此远离并移离点。最后,隐藏文本,并用注释替换它们,以将它们链接到相应的点。

    Parameters:texts (list) – A list of matplotlib.text.Text objects to adjust.

    Other Parameters:

    • x (array_like) – x-coordinates of points to repel from; if not provided only uses text coordinates.

    • y (array_like) – y-coordinates of points to repel from; if not provided only uses text coordinates

    • add_objects (list or PathCollection) – a list of additional matplotlib objects to avoid; they must have a .get_window_extent() method; alternatively, a PathCollection or a list of Bbox objects.

    • ax (matplotlib axe, default is current axe (plt.gca())) – axe object with the plot

    • expand_text (array_like, default (1.05, 1.2)) – a tuple/list/… with 2 multipliers (x, y) by which to expand the bounding box of texts when repelling them from each other.

    • expand_points (array_like, default (1.05, 1.2)) – a tuple/list/… with 2 multipliers (x, y) by which to expand the bounding box of texts when repelling them from points.

    • expand_objects (array_like, default (1.05, 1.2)) – a tuple/list/… with 2 multipliers (x, y) by which to expand the bounding box of texts when repelling them from other objects.

    • expand_align (array_like, default (1.05, 1.2)) – a tuple/list/… with 2 multipliers (x, y) by which to expand the bounding box of texts when autoaligning texts.

    • autoalign (str or boolean {‘xy’, ‘x’, ‘y’, True, False}, default ‘xy’) – Direction in wich the best alignement will be determined

      • ‘xy’ or True, best alignment of all texts determined in all directions automatically before running the iterative adjustment (overriding va and ha),
      • ‘x’, will only align horizontally,
      • ‘y’, will only align vertically,False, do nothing (i.e. preserve va and ha)
    • va (str, default ‘center’) – vertical alignment of texts

    • ha (str, default ‘center’) – horizontal alignment of texts,

    • force_text (tuple, default (0.1, 0.25)) – the repel force from texts is multiplied by this value

    • force_points (tuple, default (0.2, 0.5)) – the repel force from points is multiplied by this value

    • force_objects (float, default (0.1, 0.25)) – same as other forces, but for repelling additional objects

    • lim (int, default 500) – limit of number of iterations

    • precision (float, default 0.01) – iterate until the sum of all overlaps along both x and y are less than this amount, as a fraction of the total widths and heights, respectively. May need to increase for complicated situations.

    • only_move (dict, default {‘points’:’xy’, ‘text’:’xy’, ‘objects’:’xy’}) – a dict to restrict movement of texts to only certain axes for certain types of overlaps. Valid keys are ‘points’, ‘text’, and ‘objects’. Valid values are ‘’, ‘x’, ‘y’, and ‘xy’. For example, only_move={‘points’:’y’, ‘text’:’xy’, ‘objects’:’xy’} forbids moving texts along the x axis due to overlaps with points.

    • avoid_text (bool, default True) – whether to repel texts from each other.

    • avoid_points (bool, default True) – whether to repel texts from points. Can be helpful to switch off in extremely crowded plots.

    • avoid_self (bool, default True) – whether to repel texts from its original positions.

    • save_steps (bool, default False) – whether to save intermediate steps as images.

    • save_prefix (str, default ‘’) – if save_steps is True, a path and/or prefix to the saved steps.

    • save_format (str, default ‘png’) – if save_steps is True, a format to save the steps into.

    • add_step_numbers (bool, default True) – if save_steps is True, whether to add step numbers as titles to the images of saving steps.

    • args and kwargs – any arguments will be fed into obj:ax.annotate after all the optimization is done just for plotting the connecting arrows if required.Returns:Number of iterationReturn type:int

  • 17
    点赞
  • 50
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值