drdolphin
drdolphin

Reputation: 127

Matplotlib: legend entries with variables

I am a beginner in python, so apologies if this is a very basic question. I want legend entries to be shown dependent on input variables. I already searched for a solution, but none of the tutorials on legends seem to cover what I want to achieve. The closest match was this other solution for plt.text which works fine, but does not work for legend entries, see my code example below.

from matplotlib import pyplot as plt
import numpy as np

input_var1 = 4
input_var2 = 3

y1 = np.random.rand(10)
y2 = np.random.rand(10)
x = np.linspace(0, 9, 10)

plt.plot(x, y1)
plt.plot(x, y2)

# Neither
plt.legend("Plot with input = {}".format(input_var1))
# nor
plt.legend(f"Plot with input = {input_var1}")
# works

# but this works:
plt.text(2, 0.2, "Some text with variable = {}".format(input_var1))    

plt.show()

What am I missing?

Upvotes: 3

Views: 12214

Answers (3)

r-beginners
r-beginners

Reputation: 35115

Without bothering to create a legend, variable support is possible by specifying the label of the plot, so it can be achieved by setting it and calling plt.legend().

plt.plot(x, y1, label="Plot with input = {}".format(input_var1))
plt.plot(x, y2, label="Plot with input = {}".format(input_var2))

plt.legend()
plt.show()

enter image description here

Upvotes: 3

Tillex72
Tillex72

Reputation: 21

This also works for me:

str1 = 'Plot with input =' + str(input_var1)
str2 = 'Plot with input =' + str(input_var2)
plt.legend([str1,str2])

Upvotes: 2

jf_
jf_

Reputation: 3479

You need to pass an iterable to legend, and as you have two plots, pass two legend entries:

plt.legend(["First data with {}".format(input_var1),"Second data with {}".format(input_var2)])

Plots this: `enter image description here

Upvotes: 6

Related Questions