我找不到关于此主题的其他线程或文档 - 有没有人在 python matplotlib 包中成功下划线?对于所有其他属性,我使用的语法是这样的:
plt.text(0.05, 0.90, 'Parameters: ', fontsize=12)
但是,除了在文件中实际编码一行之外,我不知道如何在这段文本下划线。
想法?
Matplotlib 可以使用 LaTeX 处理所有文本,请参阅文档的此页以获取更多信息。在 LaTeX 中为文本添加下划线的命令很简单:
\underline
。来自示例脚本之一的文档字符串:
如果设置了
参数 text.usetex,则可以使用 TeX 渲染所有 matplotlib 文本。目前,这适用于rc
和agg
后端,并要求您在系统上正确安装 tex 和 http://matplotlib.sf.net/matplotlib.texmanager.html 中描述的其他依赖项。第一次运行脚本时,您将看到 tex 和相关工具的大量输出。下次,运行可能会很安静,因为很多信息都缓存在 ~/.tex.cache 中ps
作为一个简单的例子,我们可以这样做
import matplotlib.pyplot as plt
from matplotlib import rc
rc('text', usetex=True)
plt.sunplot(111)
plt.text(0.05, 0.90, r'\underline{Parameters}: ', fontsize=12)
获取带下划线的文本。
这是一个老问题,但我实际上需要在不使用 LaTeX 的文本下划线,所以我想我会为可能遇到同样问题的其他人跟进我提出的解决方案。
最终我的解决方案找到了相关文本对象的边界框,然后使用注释命令中的 arrowprop 参数在文本下方绘制一条直线。这种方法有一些注意事项,但总的来说,我发现它非常灵活,因为这样您就可以根据需要自定义下划线。
我的解决方案的一个例子如下:
import matplotlib.pyplot as plt
import numpy as np
def test_plot():
f = plt.figure()
ax = plt.gca()
ax.plot(np.sin(np.linspace(0,2*np.pi,100)))
text1 = ax.annotate("sin(x)", xy=(.7,.7), xycoords="axes fraction")
underline_annotation(text1)
text2 = ax.annotate("sin(x)", xy=(.7,.6), xycoords="axes fraction",
fontsize=15, ha="center")
underline_annotation(text2)
plt.show()
def underline_annotation(text):
f = plt.gcf()
ax = plt.gca()
tb = text.get_tightbbox(f.canvas.get_renderer()).transformed(f.transFigure.inverted())
# text isn't drawn immediately and must be
# given a renderer if one isn't cached.
# tightbbox return units are in
# 'figure pixels', transformed
# to 'figure fraction'.
ax.annotate('', xy=(tb.xmin,tb.y0), xytext=(tb.xmax,tb.y0),
xycoords="figure fraction",
arrowprops=dict(arrowstyle="-", color='k'))
#uses an arrowprops to draw a straightline anywhere on the axis.
需要注意的一件事是,如果您想填充下划线,或控制线条粗细(请注意,两个注释的线条粗细相同),您必须在“underline_annotation”命令中手动执行此操作,但是这个通过通过
arrowprops
字典传递更多参数,或者增加绘制线条的位置,这很容易做到。