问题
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()
回答1:
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))
来源:https://stackoverflow.com/questions/53781815/superscript-format-in-matplotlib-plot-legend