Lvpec
Lvpec

Reputation: 25

How can I label a plot using a mix of a variable and string?

I'm running into trouble when trying to label individual plots (inside a loop) using a mix of variables and strings.

Here is the section I'm having trouble with:

plt.plot(wlist, elist, label=('ratio =',i)) #using this inside a loop

When I run it, it shows up on the legend as ('ratio =', #) where the # is whatever iteration it is on. I only want it to print as:

Ratio = #

(The parenthesis I added are part of the output I'm getting)

Upvotes: 1

Views: 4477

Answers (1)

Derek O
Derek O

Reputation: 19545

If the parentheses aren't needed, then you can pass an f-string to the label argument (you can read more about f-strings here if you haven't used them before):

plt.plot(wlist, elist, label=f'ratio ={i}')

Here is a quick example borrowed from this answer where we can label some curves based on the iteration number:

import numpy as np
x = np.linspace(0, 20, 1000)
y_plots = [np.sin(x), np.cos(x)]
for i in range(len(y_plots)):
    plt.plot(x, y_plots[i], label=f"plot {i}")
plt.legend(loc='upper left')
plt.show()

enter image description here

Upvotes: 1

Related Questions