【问题标题】:Matplotlib subscript in format string [duplicate]格式字符串中的 Matplotlib 下标 [重复]
【发布时间】: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


【解决方案1】:

正如@NipunBatra 在 cmets 中所说,{LA} 似乎被理解为字符串格式的一部分。为了解决这个在{LA} 周围添加和额外的花括号。你的anchored_text 会变成:

anchored_text = AnchoredText(r"G$_{{LA}}$ = {:3.2f}*GLD + {:3.2f}\n\nPearson's R ="
                             r" {:3.2f}, SE = {:3.2f}\n $R^2$ = {:3.2f}".format(b,a,r,SE, r2), loc=2)

【讨论】:

  • 谢谢!现在完美运行。
猜你喜欢
  • 2019-07-11
  • 2013-01-17
  • 2016-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-13
  • 1970-01-01
  • 2018-06-02
相关资源
最近更新 更多