Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib - How to add multiple lines text box when using $ sign in the line I want to display?

I need to plot r squared and power law equation in two separate lines in a text box in a figure, but I can't use the '$a=3$\n$b=2$ as I already have $ sign in my code. So whenever I try to add the '& \ &' it does not work.

'y='+str(round(m,3))+'x$^{'+str(round(j,3))+'}$'

r$^{2}$=0.95

How can I display these in two lines in a box on a figure?

Thanks

like image 837
Tereza Avatar asked Nov 25 '15 11:11

Tereza


People also ask

How do I show overlapping lines in matplotlib?

How do I show overlapping lines in matplotlib? Set the figure size and adjust the padding between and around the subplots. Initialize a variable overlapping to set the alpha value of the line. Plot line1 and line2 with red and green colors, respectively, with the same alpha value.

What does %Matplotlib inline mean?

%matplotlib inline turns on “inline plotting”, where plot graphics will appear in your notebook. This has important implications for interactivity: for inline plotting, commands in cells below the cell that outputs a plot will not affect the plot.


2 Answers

I'm not sure what the problem is here. If you add those two stings together with a \n in the middle, it works for me:

import matplotlib.pyplot as plt

m,j=5.3421,2.6432

fig,ax = plt.subplots()

t='y='+str(round(m,3))+'x$^{'+str(round(j,3))+'}$\n r$^{2}$=0.95'
ax.text(0.5,0.5,t)

plt.show()

enter image description here

Alternatively, you can do this with string formatting:

t='y={:0}x$^{{{:1}}}$ \n r$^{{2}}$=0.95'.format(m,j)

Note the single braces {:0} for the format strings, and double braces {{2}} for the latex code (and therefore triple braces when you have a format string inside some latex code {{{:1}}}

like image 28
tmdavison Avatar answered Oct 11 '22 21:10

tmdavison


In case the OP wanted this:

enter image description here

Here's the code:

#!/usr/bin/python

import matplotlib
import matplotlib.pyplot

matplotlib.rc('text', usetex=True) #use latex for text

# add amsmath to the preamble
matplotlib.rcParams['text.latex.preamble']=[r"\usepackage{amsmath}"]

# data:
m, j = 5.3421, 2.6432

# insert a multiline latex expression
matplotlib.pyplot.text(0.2,0.2,

    r'\[' # every line is a separate raw string...
    r'\begin{split}' # ...but they are all concatenated by the interpreter :-)
    r'    y      &= ' + str(round(m,3)) + 'x^{' + str(round(j,3)) + r'}\\'
    r'    r^2    &= 0.95 '
    r'\end{split}'
    r'\]',

    size=50) # make it big so we can see it

matplotlib.pyplot.savefig("test.png")
like image 193
Adobe Avatar answered Oct 11 '22 20:10

Adobe