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

后端 未结 4 1204
攒了一身酷
攒了一身酷 2020-12-17 08:58

I have a very basic question : how to do a line break with matplotlib in python with an \"annotate\" command. I tried \"\\\" and \"\\n\" but it does not work. And how to do

4条回答
  •  余生分开走
    2020-12-17 09:54

    You can use the triple quotes when you define the annotation string, as in string="""some text""", so that the actual line breaks you type in your string will be interpreted as line breaks in the output. Here is an example, which includes latex and the printing of some numerical parameters from other parts of your code

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

    I have added some "extras":

    • the r soon before the opening triple quotes, to facilitate the LaTeX interpreter

    • the double curly brackets {{}}, so that the .format() command and the LaTeX don't mess with each other

    • the xycoords='axes fraction' option, so to specify the position of the string with fractional values with respect of the width and height of the plot
    • the backgroundcolor='w' option, that puts a white marquee around the annotation (convenient in case of overlapping with your plot)

    The plot obtained is this:

提交回复
热议问题