如何为matplotlib图例标签返回由分数内的上标组成的字符串? [重复]

问题描述 投票:1回答:1

这个问题在这里已有答案:

我编写了一个例程,用于绘制xy数据。此代码还计算第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是一个数字)?

python-3.x matplotlib fonts label legend
1个回答
1
投票

您可以使用字符串格式化语法%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)

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.