python Matplotlib:将文本置于其bbox中

6xfqseft  于 2023-11-15  发布在  Python
关注(0)|答案(3)|浏览(144)

我必须绘制一些数据和一些垂直线来划分有趣的间隔,然后我想使用text添加一些标签。我不能完全避免标签与数据或垂直线重叠,所以我决定在文本周围放一个bbox来保持它的可读性。我的问题是我不能在这个框内居中对齐它,这显然是在我看来,这是显而易见的,而且相当烦人。
我正在做这样的事情:

  1. import numpy
  2. import matplotlib
  3. import matplotlib.pyplot as plt
  4. fig=plt.figure()
  5. plot=fig.add_subplot(111)
  6. x=numpy.linspace(1,10,50)
  7. y=numpy.random.random(50)
  8. plot.plot(x,y)
  9. plot.text(4.5,.5,'TEST TEST',\
  10. bbox={'facecolor':'white','alpha':1,'edgecolor':'none','pad':1})
  11. plot.axvline(5,color='k',linestyle='solid')
  12. plt.show()

字符串
这将创建以下图:

这是很明显的,该文本是不是在其bbox居中.我怎么能改变这一点?我花了相当长的时间在谷歌上,但我找不到任何东西.

编辑:

谢谢你到目前为止的建议。
This表明我所看到的实际上是期望的行为。显然,matplotlib的新版本中的bbox是考虑到它所包含的文本的可能最大下降(“g”的下降)而选择的。
当一个“g”出现在文本中时,这确实看起来很好:

不幸的是,在我的例子中没有“g”或类似的下降。

atmip9wb

atmip9wb1#

使用文本属性hava

  1. plot.text(5.5,.5,'TEST TEST TEST TEST',
  2. bbox={'facecolor':'white','alpha':1,'edgecolor':'none','pad':1},
  3. ha='center', va='center')

字符串
要进行检查,请在图的中心绘制线条:

  1. plot.axvline(5.5,color='k',linestyle='solid')
  2. plot.axhline(0.5,color='k',linestyle='solid')

c6ubokkw

c6ubokkw2#

现在似乎有了在坐标系中正确选择position the text的选项(特别是新的va = 'baseline')。然而,正如用户35915所指出的,这不会改变框相对于文本的对齐方式。这种对齐方式在个位数中尤其明显,特别是数字“1”(参见this bug)。在此之前,我的解决方法是手动放置矩形,而不是通过bbox参数:

  1. import matplotlib.pyplot as plt
  2. import matplotlib.patches as patches
  3. # define the rectangle size and the offset correction
  4. rect_w = 0.2
  5. rect_h = 0.2
  6. rect_x_offset = 0.004
  7. rect_y_offset =0.006
  8. # text coordinates and content
  9. x_text = 0.5
  10. y_text = 0.5
  11. text = '1'
  12. # create the canvas
  13. fig,ax = plt.subplots(figsize=(1,1),dpi=120)
  14. ax.set_xlim((0,1))
  15. ax.set_ylim((0,1))
  16. # place the text
  17. ax.text(x_text, y_text, text, ha="center", va="center", zorder=10)
  18. # compare: vertical alignment with bbox-command: box is too low.
  19. ax.text(x_text+0.3, y_text, text, ha="center", va="center",
  20. bbox=dict(facecolor='wheat',boxstyle='square',edgecolor='black',pad=0.1), zorder=10)
  21. # compare: horizontal alignment with bbox-command: box is too much to the left.
  22. ax.text(x_text, y_text+0.3, text, ha="center", va="center",
  23. bbox=dict(facecolor='wheat',boxstyle='square',edgecolor='black',pad=0.2), zorder=10)
  24. # create the rectangle (below the text, hence the smaller zorder)
  25. rect = patches.Rectangle((x_text-rect_w/2+rect_x_offset, y_text-rect_h/2+rect_y_offset),
  26. rect_w,rect_h,linewidth=1,edgecolor='black',facecolor='white',zorder=9)
  27. # add rectangle to plot
  28. ax.add_patch(rect)
  29. # show figure
  30. fig.show()

字符串


的数据

展开查看全部
q8l4jmvw

q8l4jmvw3#

您可以使用text函数的verticalalignmenthorizontalalignment参数来将文本精确定位在边界框内。以下是更新后的代码:

  1. plot.text(4.5, 0.5, 'TEST TEST',
  2. bbox={'facecolor': 'white', 'alpha': 1, 'edgecolor': 'none', 'pad': 1},
  3. verticalalignment='center', horizontalalignment='center')

字符串

相关问题