【发布时间】:2017-07-10 20:12:26
【问题描述】:
我知道在here 之前有人问过这个问题,但给出的答案对我不起作用.. 当我将 {} 放在我的下标周围时,我得到一个键错误。无论我使用“G${LA}$”还是“G{LA}”都会发生这种情况。
作为编辑,这是我正在使用的代码的简化版本:
X=np.array(random.sample(range(1000),10))
Y=np.array(random.sample(range(1000),10))
plt.clf()
f, ax =plt.subplots(1,1)
b, a = np.polyfit(X,Y, 1)
# 3.5 Calculate Pearson's correlation
r, SE = stats.pearsonr(X, Y)
r2 = r*r
# 3.6 Regression line to be added to plot - anchored text automatically locates the text, without the need to specifying the x,y coordinates
anchored_text = AnchoredText("GLA = {:3.2f}*GLD + {:3.2f}\n\nPearson's R = {:3.2f}, SE = {:3.2f}\n $R^2$ = {:3.2f}".format(b,a,r,SE,r2), loc=2)
# 3.7 Plot
ax = sns.regplot(X, Y, color='g')
ax.add_artist(anchored_text)
plt.show()
现在,如果我添加下标,它会抛出错误:
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-31-00e10c71309f> in <module>()
19
20 # 3.6 Regression line to be added to plot - anchored text automatically locates the text, without the need to specifying the x,y coordinates
---> 21 anchored_text = AnchoredText(r"G$_{LA}$ = {:3.2f}*GLD + {:3.2f}\n\nPearson's R = {:3.2f}, SE = {:3.2f}\n $R^2$ = {:3.2f}".format(b,a,r,SE, r2), loc=2)
22
23 # 3.7 Plot
KeyError: 'LA'
会是因为我使用的是 AnchoredText 吗?或者自从发布另一个帖子后有什么变化?
【问题讨论】:
-
可能......但仍然存在相同的错误。
-
你能提供你使用的代码吗?更好的是Minimal, Complete, and Verifiable Example。
-
如果你写:
format(10, b,a,r,SE, r2)。我想知道{}是否被理解为字符串格式的一部分?! -
@NipunBatra 你可能是对的。如果您删除其他所有内容并只使用
r"$G_{LA}$",那么问题就会消失。 -
@DavidG:在那种情况下,也许只是写成:
AnchoredText(r"G$_{}$ = {:3.2f}*GLD + {:3.2f}\n\nPearson's R = {:3.2f}, SE = {:3.2f}\n $R^2$ = {:3.2f}".format("LA", b,a,r,SE, r2), loc=2)
标签: python matplotlib string-formatting