簡體   English   中英

Python:Matplotlib注釋換行符(有和沒有乳膠)

[英]Python : Matplotlib annotate line break (with and without latex)

我有一個非常基本的問題:如何使用“annotate”命令在python中使用matplotlib進行換行。 我試過“\\”和“\\ n”,但它不起作用。 以及如何為“Latex”注釋和普通文本注釋執行此操作?

非常感謝你。

你究竟嘗試了什么?

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

在此輸入圖像描述

但是,如果您需要兩者,請考慮以下示例:

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就不會相互.format()

  • xycoords='axes fraction'選項,因此要指定字符串的位置,其中小數值與繪圖的寬度和高度有關
  • backgroundcolor='w'選項,在注釋周圍放置一個白色選框(方便與你的情節重疊)

獲得的情節如下: 在此輸入圖像描述

快速解決方案

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM