在python中的图例标签上包含带有特殊字符的变量

在python中的图例标签上包含带有特殊字符的变量,python,matplotlib,legend,Python,Matplotlib,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}$") 如果我删除变量,则应等同于以下内容: mainax.plot(x, y, label=r"power law, $n$ = 2.1 $\times$ 10$^{12}$ c

这是我代码的一部分,我希望图例中有一些变量:

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

mainax.plot(x, y, label=r"power law, $n$ =" + c1 + "$\times$ 10$^" + c2 + "cm$^{-3}$")
如果我删除变量,则应等同于以下内容:

mainax.plot(x, y, label=r"power law, $n$ = 2.1 $\times$ 10$^{12}$ cm$^{-3}$")
我最后想要的应该是这样的:


您可以使用
.format
字符串格式选项来获取所需的标签。在这里,您必须确保有正确数量的大括号,因为
.format
占用其中一个大括号:

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

DavidG谢谢你的回答。