1

I'm trying to plot multiple histograms in the same subplot, and also add legends to it. The legends requires a string for each label. For each string, I'm using mathematical expressions, but I will also need to include a variable to it.

To be more specific, for each legend lable, I want it to look like r"$\mathcal{M}_{j}$" where j is a variable that I go through using a for loop. I checked the Matplotlib official documentation, but there's no mentioning of this kind of usage. I also did a lot of google searching without results.

I also included a simplified code here to explain the problem more clearly:

code

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)

the following graph is what I got right now: please click here for image

I want the legends to look like $\mathcal{M}_{j}$ where j is the index of the model.

1 Answers1

0

As @ImportanceOfBeingErnest has pointed out,

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

is the answer. Well, I feel kind of stupid. But in my defense I have always had the impression that a raw string is needed for a mathematical format string. Clearly this is not the case.

But there came more confusion: in the documentation of matplotlib it does say a raw string is needed for math expression. Why don't we need it now?