FABeng
FABeng

Reputation: 83

Matplotlib legend with line breaks

I am trying to add my regression coefficients as LaTeX formulas into the legends of subplots, which have multiple lines:

fig, ((plt1, plt2, plt3), (plt4, plt5, plt6)) = plt.subplots(2, 3, figsize=(22,10), sharex='col', sharey='row')

plot1, = plt1.plot('Normalized Times','Mean', linestyle='None', marker='o', color='#6E9EAF', markersize=marksize, data=Phase1_Temp)

plot1_R, = plt1.plot(Xdata_Phase1_Temp, Y_Phase1_Temp_Pred, linewidth=width_line, color=Orange)

plt1.legend([plot1_R], ["$f(x) = {m}*x +{b}$".format(m=np.round(A[1],2), b=np.round(A[0],2)) "\n" "$R2 = {r}$".format(r=np.round(A[2],2))])

When I run the file I get invalid syntax when I call a second label for one handle:

  "\n" "$R2 = {r}$".format(r=np.round(A[2],2))])
       ^
SyntaxError: invalid syntax

Anyone knows how to fix this?

Upvotes: 0

Views: 14667

Answers (2)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339122

Consider using a single string to format

import matplotlib.pyplot as plt

A = [5,4,3]

fig, ((ax1, ax2, ax3), (ax4, ax5, ax6)) = plt.subplots(2, 3, figsize=(22,10), sharex='col', sharey='row')

plot1, = ax1.plot([0,1], linestyle='None', marker='o', color='#6E9EAF', markersize=5)

plot1_R, = ax1.plot([0,1], linewidth=2, color="orange")

ax1.legend([plot1_R], 
           ["$f(x) = {m}*x +{b}$\n$R2 = {r}$".format(m=np.round(A[1],2), 
                                                     b=np.round(A[0],2), r=np.round(A[2],2))])

plt.show()

enter image description here

Also, f-strings might become handy here, where rounding is performed at the formatting level.

ax1.legend([plot1_R], [f"$f(x) = {A[1]:.2f}*x +{A[0]:.2f}$\n$R2 = {A[2]:.2f}$"])

enter image description here

Upvotes: 3

adrtam
adrtam

Reputation: 7211

In python, you can concatenate strings like this:

"hello " "world"

and produce "hello world". But if you do this, it is a syntax error:

"{} ".format("hello") "world"

So if you want to concatenate from the output of format(), use +:

"{} ".format("hello") + "world"

And in your case (line break added for readability):

plt1.legend([plot1_R], [
    "$f(x) = {m}*x +{b}$".format(m=np.round(A[1],2), b=np.round(A[0],2))
    + "\n"
    + "$R2 = {r}$".format(r=np.round(A[2],2))
])

Upvotes: 0

Related Questions