这个问题在这里已有答案:
我编写了一个例程,用于绘制x
和y
数据。此代码还计算第n个导数d/dx^n (y)
改变符号的索引,其中n
被指定为函数参数。我想在matplotlib图中将这个衍生物作为图例标签包含在内。
如果预先确定,我可以创建一个标签来包含它。例如,如果n
预先确定为2
,那么:
label = r'$\frac{d^2y}{dx^2}$'
但由于n
是一个函数参数,我不知道如何将它分配给分数。作为示例(包含失败的尝试),请参阅以下内容:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(1, 10, 10)
y = x
def f(x, y, n):
""" """
fig, ax = plt.subplots()
if n == 1:
label = r'$\frac{dy}{dx} = 0$'
else:
numerator = 'd^{}y'.format(n)
denominator = 'dx^{}'.format(n)
# label = r'$\frac{}{}$'.format(numerator, denominator)
# label = '$\frac{}{}$'.format(numerator, denominator)
# label = '$\frac{numerator}{denominator}$'
label = r'$\frac{numerator}{denominator}$'
ax.scatter(x, y, c='r', marker='.', s=5, label=label)
ax.legend(loc='upper left')
plt.show()
plt.close(fig)
f(x, y, n=1)
f(x, y, n=2)
我只关注传奇标签。我怎样才能使得我得到一个字符串分数的所需输出,其分子显示为r'$d^ny$'
,其分母显示为r'$dx^n$'
(其中n
是一个数字)?
您可以使用字符串格式化语法%s
执行以下操作:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(1, 10, 10)
y = x
def f(x, y, n):
""" """
fig, ax = plt.subplots()
if n == 1:
label = r'$\frac{dy}{dx} = 0$'
else:
numerator = 'd^{}y'.format(n)
denominator = 'dx^{}'.format(n)
label = r'$\frac{%s}{%s}$' %(numerator, denominator)
ax.scatter(x, y, c='r', marker='.', s=5, label=label)
ax.legend(loc='upper left', fontsize=18)
plt.show()
plt.close(fig)