Matplotlib text dimensions

前端 未结 4 1121
青春惊慌失措
青春惊慌失措 2020-11-30 03:08

Is it possible to determine the dimensions of a matplotlib text object? How can I find the width and height in pixels?

Thanks

Edit: I think

4条回答
  •  忘掉有多难
    2020-11-30 03:58

    I could not find a way to get the text extents as rendered on a plot even after a draw() event.

    But here's a way to render just the text and get all kinds of geometric information from it:

    t = matplotlib.textpath.TextPath((0,0), 'hello', size=9, prop='WingDings')
    bb = t.get_extents()
    
    #bb:
    #Bbox(array([[  0.759375 ,   0.8915625],
    #            [ 30.4425   ,   5.6109375]]))
    
    w = bb.width   #29.683125
    h = bb.height  #4.7193749
    

    Edit

    I've been playing with this for a bit and I have an inconsistency I can't get figured out. Maybe someone else can help. The scale seems off and I don't know if it's a dpi issue or a bug or what, but this example pretty much explains:

    import matplotlib
    from matplotlib import pyplot as plt
    plt.cla()
    
    p = plt.plot([0,10],[0,10])
    
    #ffam = 'comic sans ms'
    #ffam = 'times new roman'
    ffam = 'impact'
    fp = matplotlib.font_manager.FontProperties(
        family=ffam, style='normal', size=30,
        weight='normal', stretch='normal')
    
    txt = 'The quick brown fox'
    plt.text(100, 100, txt, fontproperties=fp, transform=None)
    
    pth = matplotlib.textpath.TextPath((100,100), txt, prop=fp)
    bb = pth.get_extents()
    
    # why do I need the /0.9 here??
    rec = matplotlib.patches.Rectangle(
        (bb.x0, bb.y0), bb.width/0.9, bb.height/0.9, transform=None)
    plt.gca().add_artist(rec)
    
    plt.show()
    

提交回复
热议问题