我想在 matplotlib 标题中包含符号,但以下代码不起作用。
import matplotlib.pyplot as plt
import numpy as np
N_combs=10
t1 = np.random.randint(100, size=(N_combs,2))
g1=np.random.randint(100, size=(N_combs,2))
plt.plot(range(100), np.random.randn(100, N_combs))
plt.title([rf'$\tau_c1={x} \tau_c2={y} \Delta G_{{01}}={i} \Delta G_{{01}}={j}$' for x,y in t1[0] for i,j in g1[0]])
Run Code Online (Sandbox Code Playgroud)
错误:
File "<ipython-input-972-589f95b4b1cf>", line 8, in <module>
plt.title([rf'$\tau_c1={x} \tau_c2={y} \Delta G_{{01}}={i} \Delta G_{{01}}={j}$' for x,y in t1[0] for i,j in g1[0]])
File "<ipython-input-972-589f95b4b1cf>", line 8, in <listcomp>
plt.title([rf'$\tau_c1={x} \tau_c2={y} \Delta G_{{01}}={i} \Delta G_{{01}}={j}$' for x,y in t1[0] for i,j in g1[0]])
TypeError: cannot unpack non-iterable numpy.int32 object
Run Code Online (Sandbox Code Playgroud)
相反,如果我使用 plt.legend,它就可以工作。
将每个 Latex 字符串与格式化函数结合起来。
(plt.title(r'$\tau_c1=$'+'{}'.format(t1[0][0])
+r'$\tau_c2=$'+'{}'.format(t1[0][1])
+r'$\Delta G_{{01}}=$'+'{}'.format(g1[0][1])
+r'$\Delta G_{{01}}=$'+'{}'.format(g1[0][1]))
Run Code Online (Sandbox Code Playgroud)