【问题标题】:Using placeholders (%d,%s) in plt.text (matplotlib.pyplot.text)在 plt.text (matplotlib.pyplot.text) 中使用占位符 (%d,%s)
【发布时间】:2016-10-14 10:52:38
【问题描述】:

我在使用 plt.text 命令为带注释的文本(在这种情况下为平均值和标准差)分配数值时遇到问题。

因为我有六个子图,所以我想自动化这个过程,而不是一个一个地写。下面附上包含问题的代码sn-p:

# var=dictionary containing output variables
  b=1
> for i in var: 
>    
>     # Created Subplots for different vectors (includes labelling of axes) here

      # Mean[] is an array containing mean values for all the plots

      plt.text(X_cord,Y_cord, r'$\mu=$' %d, %d (Mean[b-1]), fontsize=14) 
>       
>     #tick-properties
>    
>     # Setting limits for axes
>     b+=1

我对 Python 比较陌生,因此不太了解如何在 Python 中使用占位符。我在网上搜索,但修复并没有太大帮助。

我的问题有两个方面:我可以使用 plt.text 下的占位符 (%d) 来调用包含所有方法的数组元素吗?如果是那怎么办?

【问题讨论】:

  • 你来自什么编码背景?如果我能解释与您熟悉的相关的 Python 机制,我可以为您提供更多帮助。
  • 感谢您的关注:)。 Herbst 先生已在下方成功回答了该问题。我来自 C 和 Matlab 背景。由于我来自机械工程背景,因此对这些也没有广泛的了解。

标签: python matplotlib tex


【解决方案1】:

尝试以下方法:

for i, _ in enumerate(var): 
    plt.text(X_cord,Y_cord, r'$\mu=%s$' % (Mean[i]), fontsize=14)

我更喜欢使用字符串方法.format

for i, _ in enumerate(var): 
    plt.text(X_cord,Y_cord, r'$\mu={}$'.format(Mean[i]), fontsize=14)

【讨论】:

  • 感谢您分享此内容。第二个修复似乎在稍作调整后起作用(在大括号后添加 $ )。但是,第一个修复不起作用。不知道为什么。
  • 我对第一个解决方案也有问题。您在% 之后输入的字母会影响结果。对于提供的数据类型,使用的字母必须正确。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-07
  • 2020-10-12
  • 1970-01-01
  • 2015-05-13
  • 2013-10-16
  • 2015-09-05
相关资源
最近更新 更多