【问题标题】:Python : Matplotlib annotate line break (with and without latex)Python:Matplotlib 注释换行符(有和没有乳胶)
【发布时间】:2012-04-23 16:55:31
【问题描述】:

我有一个非常基本的问题:如何使用“注释”命令在 python 中使用 matplotlib 进行换行。我尝试了“\”和“\n”,但它不起作用。以及如何为“Latex”注释和普通文本注释执行此操作?

非常感谢。

【问题讨论】:

标签: python latex matplotlib


【解决方案1】:

你到底尝试了什么?

您是否偶然使用了原始字符串(例如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()

【讨论】:

  • 如果我想把文字移到图的外面怎么办?比如左上角?
  • @FC84 - 在这种情况下,以坐标轴坐标指定文本的 x,y 位置。例如,这会将文本 5 points 放置在坐标区右上角的右侧:ax.annotate('blah', xy=(1, 1), xytext=(5, 0), xycoords='axes fraction', textcoords='offset points')
【解决方案2】:

但是,如果您需要两者,请考虑以下示例:

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)。

【讨论】:

    【解决方案3】:

    您可以在定义注释字符串时使用三引号,如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() 使用${} 作为占位符。
    • 嗨,Jason,确实,美元符号之间的“I =”由 LaTeX 解释,并以斜体绘制。数值不是,而且确实不是斜体。我没有特别的理由将数值排除在外。抱歉,如果这造成了一些混乱..
    【解决方案4】:

    快速解决方案

    plt.annotate("I am \n"+r"$\frac{1}{2}$"+"\n in latex math environment", xy=(0.5, 0.5))

    【讨论】:

      猜你喜欢
      • 2011-02-08
      • 2011-01-12
      • 1970-01-01
      • 2017-09-14
      • 1970-01-01
      • 2023-04-01
      • 1970-01-01
      • 2017-09-19
      • 1970-01-01
      相关资源
      最近更新 更多