这是我的代码的一部分,我想在图例中添加一些变量:
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()
关于python - 在python中包含带有特殊字符的图例标签上的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54785758/