2017-11-25 193 views
0

我上动态曲线工作jupyter与matplotlib,这意味着在for循环中每个不同的循环提供了一个不同的曲线图,如下面动态胶乳代码在matplotlib标题

import matplotlib.pyplot as plt 
import numpy as np 
import time 
import matplotlib as mpl 
mpl.rcParams['lines.linewidth'] = 2 
plt.ion() 
%matplotlib notebook 

x = np.arange(-10, 10, 0.01) 

fig = plt.figure(figsize = (12, 7)) 
ax = fig.add_subplot(111) 
ax.grid() 
plt.show() 
for j in range(1,5): 
    ax.set_title(r"%6.2f $y = \frac{\sin{(\pi x j)}}{(\pi x j)}$" % j) 
    y = np.sin(np.pi*x*j)/(np.pi*x*j) 
    line, = ax.plot(x, y, 'b') 
    fig.canvas.draw() 
    time.sleep(1) 
    if j != 4: 
     line.remove() 

线的例子“斧头.set_title“提供的标题既有恒定的乳胶代码,也有随时间变化的数字。我的问题是,我可以在标题中更改乳胶代码中的数字,但我真的不知道如何更改乳胶代码中的内容。

在前面的例子中,对于每一个不同的循环,我想不仅是一个不同的情节,但也有不同的乳胶码标题,问题报告,提供了不同的结果

enter image description here

有任何人都可以为我提供任何关于它的信息

+1

@ImportanceOfBeingErnest - 只是因为你使用'.format()'。 OP使用'%'格式化,第二个问题的答案显示了一个完全有效的解决方案:'r'%(j)6.2f $ y = \ frac {\ sin {(\ pi x%(j)6.2 f)}} {(\ pi x%(j)6.2f)} $“%{'j':j}' – Craig

回答

1

使用format表示法是有意义的。
然后,您需要转义所有需要成为MathText字符串一部分的大括号。

plt.title(r"$y = \frac{{\sin{{({j}\pi)}}}}{{({j}\pi)}}$".format(j=3.14159265359)) 

enter image description here

要格式化format符号的数字,你可以定义小数位({j:.3f})的数量或使用常规数字格式({j:g})。

plt.title(r"$y = \frac{{\sin{{({j:.3f}\pi)}}}}{{({j:g}\pi)}}$".format(j=3.14159265359)) 

enter image description here

+1

太棒了! –

+0

等等,你能结合r-和f-字符串吗? –

+0

@PaulH呃,你不需要'r“”'因为反斜杠可以被转义“\\”。但是因为我很少编写纯python 3的代码,所以我从来没有使用过'f“”'。 – ImportanceOfBeingErnest