我必须绘制一些数据和一些垂直线来划定有趣的间隔,然后我想添加一些标签text
.我不能完全避免标签与数据或垂直线重叠,所以我决定bbox
在文本周围放置以保持可读性.我的问题是我无法在此框中集中对齐它,这在我看来是清晰可见的并且非常烦人.
我正在做这样的事情:
import numpy
import matplotlib
import matplotlib.pyplot as plt
fig=plt.figure()
plot=fig.add_subplot(111)
x=numpy.linspace(1,10,50)
y=numpy.random.random(50)
plot.plot(x,y)
plot.text(4.5,.5,'TEST TEST',\
bbox={'facecolor':'white','alpha':1,'edgecolor':'none','pad':1})
plot.axvline(5,color='k',linestyle='solid')
plt.show()
Run Code Online (Sandbox Code Playgroud)
很明显,文本并不以其为中心bbox
.我怎么能改变这个?我花了很长时间在Google上,但我找不到任何东西.
编辑:
感谢您的建议到目前为止.
这表明我所看到的实际上是所希望的行为.显然bbox
,新版本的matplotlib
选择考虑了它所包含的文本可能的最大下降('g'的下降).
当文本中出现"g"时,这确实看起来很好:
不幸的是,在我的情况下,没有'g'或任何类似下降的东西.有没有人有任何进一步的想法?
使用文本属性ha和va:
plot.text(5.5,.5,'TEST TEST TEST TEST',
bbox={'facecolor':'white','alpha':1,'edgecolor':'none','pad':1},
ha='center', va='center')
Run Code Online (Sandbox Code Playgroud)
要进行检查,请在图的中心绘制线条:
plot.axvline(5.5,color='k',linestyle='solid')
plot.axhline(0.5,color='k',linestyle='solid')
Run Code Online (Sandbox Code Playgroud)
似乎现在有一些选项可以在坐标系中正确定位文本(特别是新的va = 'baseline'
)。然而,正如 user35915 所指出的,这不会改变框相对于文本的对齐方式。这种错位在单位数字中尤其明显,特别是数字“1”(另请参阅此错误)。在解决此问题之前,我的解决方法是手动放置矩形,而不是通过 bbox 参数:
import matplotlib.pyplot as plt
import matplotlib.patches as patches
# define the rectangle size and the offset correction
rect_w = 0.2
rect_h = 0.2
rect_x_offset = 0.004
rect_y_offset =0.006
# text coordinates and content
x_text = 0.5
y_text = 0.5
text = '1'
# create the canvas
fig,ax = plt.subplots(figsize=(1,1),dpi=120)
ax.set_xlim((0,1))
ax.set_ylim((0,1))
# place the text
ax.text(x_text, y_text, text, ha="center", va="center", zorder=10)
# compare: vertical alignment with bbox-command: box is too low.
ax.text(x_text+0.3, y_text, text, ha="center", va="center",
bbox=dict(facecolor='wheat',boxstyle='square',edgecolor='black',pad=0.1), zorder=10)
# compare: horizontal alignment with bbox-command: box is too much to the left.
ax.text(x_text, y_text+0.3, text, ha="center", va="center",
bbox=dict(facecolor='wheat',boxstyle='square',edgecolor='black',pad=0.2), zorder=10)
# create the rectangle (below the text, hence the smaller zorder)
rect = patches.Rectangle((x_text-rect_w/2+rect_x_offset, y_text-rect_h/2+rect_y_offset),
rect_w,rect_h,linewidth=1,edgecolor='black',facecolor='white',zorder=9)
# add rectangle to plot
ax.add_patch(rect)
# show figure
fig.show()
Run Code Online (Sandbox Code Playgroud)