matplotlib图例中的上标格式 [英] Superscript format in matplotlib plot legend

查看:96
本文介绍了matplotlib图例中的上标格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用奇妙的scipy曲线拟合进行曲线拟合.在绘制数据并添加图例标签以显示计算的参数时,使用 $^{}$ 使位之间的上标仅在写入字符串时有效,而在从字符串格式调用时无效.即 $ x ^ {} $.format(3)格式不正确,但 $ x ^ 3 $ 正确.

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()

推荐答案

为了让 MathText 解释大括号,它们在格式化后仍然需要存在.因此,您将需要使用一对大括号,内部用于格式化,外部用于 MathText 功能.然后仍然需要转义外部的那些,以便不用于格式化.这导致3个花括号.

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))

这篇关于matplotlib图例中的上标格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆