【问题标题】:Can I include a variable inside a mathematical expression raw string?我可以在数学表达式原始字符串中包含一个变量吗?
【发布时间】:2019-08-07 01:12:34
【问题描述】:

我正在尝试在同一个子图中绘制多个直方图,并为其添加图例。图例要求每个标签都有一个字符串。对于每个字符串,我都使用数学表达式,但我还需要在其中包含一个变量。

更具体地说,对于每个图例标签,我希望它看起来像 r"$\mathcal{M}_{j}$" 其中 j 是我使用 for 循环遍历的变量。 我检查了Matplotlib official documentation,但没有提到这种用法。我也做了很多谷歌搜索但没有结果。

我还在这里包含了一个简化的代码来更清楚地解释问题:

代码

import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np


n = 3 # number of subplots
m = 4 # number of histograms in each subplot

fig, axs = plt.subplots(nrows=n, ncols=1)

for ax in axs.reshape(-1):

    # put data to be plotted in this subplot in a list
    data_plot = []

    # list for legend label
    model_label_array = []

    for j in range(0, m):

        # generate random numbers to be plotted
        data_plot.append(np.randn(100))

        # generate label string for this group of data
        model_label_array.append("$\mathcal{M}_{str(j)}$")

    # plot
    ax.hist(data_plot,
            label=model_label_array)

下面的图表是我现在得到的: please click here for image

我希望图例看起来像 $\mathcal{M}_{j}$ 其中 j 是模型的索引。

【问题讨论】:

  • 您可能对原始字符串和 f 字符串感到困惑吗?
  • @DanielRoseman 好像我想在原始字符串中添加一个 f 字符串函数。有没有办法实现它?
  • f"$\mathcal{{M}}_{j}$"
  • 谢谢,这成功了。
  • @ImportanceOfBeingErnest 谢谢,您提供的代码有效。但我在这里有点困惑,因为documentation of matplotlib 显然表示需要一个原始字符串。我想知道为什么这里可以使用 f 字符串?

标签: python string matplotlib mathematical-expressions


【解决方案1】:

正如@ImportanceOfBeingErnest 指出的那样,

f"$\mathcal{{M}}_{j}$"

就是答案。嗯,我觉得有点傻。但在我的辩护中,我一直认为数学格式字符串需要原始字符串。显然情况并非如此。

但是出现了更多的混乱:在documentation of matplotlib 中确实说数学表达式需要原始字符串。为什么我们现在不需要它?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-22
    • 2012-09-10
    • 2022-10-15
    • 1970-01-01
    • 2021-10-20
    • 1970-01-01
    • 2018-01-18
    • 1970-01-01
    相关资源
    最近更新 更多