Radvin
Radvin

Reputation: 163

Including a variable on legend label with special characters in python

Here is part of my code and I would like to have some variables in the legend:

c1 = raw_input("enter c1: ")
c2 = raw_input("c2: ")

mainax.plot(x, y, label=r"power law, $n$ =" + c1 + "$\times$ 10$^" + c2 + "cm$^{-3}$")

It should be equivalent to the following if I remove the variables:

mainax.plot(x, y, label=r"power law, $n$ = 2.1 $\times$ 10$^{12}$ cm$^{-3}$")

What I want at the end should be something like this:

enter image description here

Upvotes: 1

Views: 4671

Answers (1)

DavidG
DavidG

Reputation: 25362

You can use the .format string formatting options in order to get the label that you want. Here you must make sure that you have the right number of curly braces as the .format takes up one of them:

c1 = "2.1"
c2 = "12"
label = r'power law, $n$ = {} $\times$ 10$^{{{}}}$ cm$^{{-3}}$'.format(c1, c2)

plt.plot([1,2], [1,2], label=label)
plt.legend()

plt.show()

enter image description here

Upvotes: 3

Related Questions