Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

python - Superscript format in matplotlib plot legend

I'm doing some curve fitting with the wonderful scipy curve fit. When plotting the data and adding a legend label to display the parameters calculated, using $^{}$ to make the between bit superscript only works when the string is written and not when called from the string format. i.e, $x^{}$.format(3) doesn't format correctly but $x^3$ does.

Should this work? Do i need to do something else if i'm providing input to the legend label?

Example code and plot below. Thanks.

import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit

x_data = np.linspace(0.05,1,101)
y_data = 1/x_data
noise = np.random.normal(0, 1, y_data.shape)
y_data2 = y_data + noise

def func_power(x, a, b):
    return a*x**b 

popt, pcov= curve_fit(func_power, x_data, y_data2)

plt.figure()
plt.scatter(x_data, y_data2, label = 'data')
plt.plot(x_data, popt[0] * x_data ** popt[1], label = ("$y = {}x^{}$").format(round(popt[0],2), round(popt[1],2)))
plt.plot(x_data, x_data**3, label = '$x^3$')
plt.legend()
plt.show()

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In order to have MathText interprete the curly brackets they still need to be present after formatting. So you will want to use a pair of curly brackets, the inner ones for formatting, the outer ones for MathText functionality. The outer ones then still need to be escaped in order not to be used for formatting. This leads to 3 curly brackets.

label = ("$y = {{{}}}x^{{{}}}$").format(round(popt[0],2), round(popt[1],2))

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...