Q:

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:

A:

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()

