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
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.
%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.
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()
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}}}
In case the OP wanted this:
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With