我试着在同一个子图中绘制多个直方图,并在其中添加图例。图例要求每个标签都有一个字符串。对于每个字符串,我都使用数学表达式,但我还需要在其中包含一个变量。你知道吗
更具体地说,对于每个图例标签,我希望它看起来像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}{uj}$,其中j是模型的索引。你知道吗
正如@ImportanceOfBeingErnest所指出的
这就是答案。嗯,我觉得有点傻。但在我的辩护中,我一直有这样一种印象:数学格式的字符串需要一个原始字符串。显然不是这样。你知道吗
但是出现了更多的混乱:在documentation of matplotlib中,它确实表示数学表达式需要一个原始字符串。为什么我们现在不需要呢?你知道吗
相关问题 更多 >
编程相关推荐