【发布时间】:2012-04-23 16:55:31
【问题描述】:
我有一个非常基本的问题:如何使用“注释”命令在 python 中使用 matplotlib 进行换行。我尝试了“\”和“\n”,但它不起作用。以及如何为“Latex”注释和普通文本注释执行此操作?
非常感谢。
【问题讨论】:
标签: python latex matplotlib
我有一个非常基本的问题:如何使用“注释”命令在 python 中使用 matplotlib 进行换行。我尝试了“\”和“\n”,但它不起作用。以及如何为“Latex”注释和普通文本注释执行此操作?
非常感谢。
【问题讨论】:
标签: python latex matplotlib
你到底尝试了什么?
您是否偶然使用了原始字符串(例如r"whatever")?
'\n' 完美运行,但如果您使用原始字符串来避免将乳胶序列解释为转义,python 会将其解释为 '\' 和 'n' 而不是换行符。
举个例子:
import matplotlib.pyplot as plt
plt.annotate('Testing\nThis\nOut', xy=(0.5, 0.5))
plt.show()
另一方面,如果我们使用原始字符串:
import matplotlib.pyplot as plt
plt.annotate(r'Testing\nThis\nOut', xy=(0.5, 0.5))
plt.show()
【讨论】:
ax.annotate('blah', xy=(1, 1), xytext=(5, 0), xycoords='axes fraction', textcoords='offset points')
但是,如果您需要两者,请考虑以下示例:
import matplotlib.pyplot as plt
a = 1.23
b = 4.56
annotation_string = r"Need 1$^\mathsf{st}$ value here = %.2f" % (a)
annotation_string += "\n"
annotation_string += r"Need 2$^\mathsf{nd}$ value here = %.2f" % (b)
plt.annotate(annotation_string, xy=(0.5, 0.5))
plt.show()
这给了你:
关键是事先组装字符串,使用+=。这样一来,您就可以在同一个注解中包含原始字符串命令(由 r 指示)和换行符 (\n)。
【讨论】:
您可以在定义注释字符串时使用三引号,如string="""some text""",这样您在字符串中键入的实际换行符将被解释为输出中的换行符。这是一个示例,其中包括乳胶和代码其他部分的一些数字参数的打印
import matplotlib.pyplot as plt
I = 100
T = 20
annotation_string = r"""The function plotted is:
$f(x) \ = \ \frac{{I}}{{2}} \cos\left(2 \pi \ \frac{{x}}{{T}}\right)$
where:
$I = ${0}
$T = ${1}""".format(I, T)
plt.annotate(annotation_string, xy=(0.05, 0.60), xycoords='axes fraction',
backgroundcolor='w', fontsize=14)
plt.show()
我添加了一些“额外”:
开三引号前的r,方便LaTeX解释器
双大括号{{}},这样.format()命令和LaTeX就不会互相混淆了
xycoords='axes fraction' 选项,所以要指定位置
具有相对于宽度和小数值的字符串
地块高度backgroundcolor='w' 选项,在周围放置一个白色选框
注释(方便与您的情节重叠)【讨论】:
$I = ${0} 行没有被解释为两个$s 之间的Latex?
.format() 使用${} 作为占位符。
快速解决方案
plt.annotate("I am \n"+r"$\frac{1}{2}$"+"\n in latex math environment", xy=(0.5, 0.5))
【讨论】: