Python:在loglog规模中绘制错误栏,在循环中绘制,然后保存图像

时间:2016-05-12 10:37:12

标签: python plot errorbar loglog

我需要绘制58个文件。其中一些是空的(不重要,我已经用if条件跳过了它们)。我需要使用带有错误栏的loglog刻度来绘制文件中的数据。我想最终保存这些情节。 我正在使用Python,spyder。 我写了以下代码:

route='/......./'
L=np.arange (1,59, 1)
for i in range (L.shape[0]):
    I=L[i]
    name_sq= 'Spectra_without_quiescent_'+('{}'.format(I))+'.dat' 
    Q=np.loadtxt(route+name_sq)
    if (len(Q) != 0):
        x=Q[:,1]
        y=Q[:,2]
        z=Q[:,3]
        fig=plt.errorbar(x,y,yerr=z, fmt = 'b')
        fig.set_yscale('log')
        fig.set_xscale('log')
        xlabel='Frequency'
        ylabel='Flux'
        title='Spectrum_'+('{}'.format(I))+'.dat'
        name='Spectrum_without_quiescent_'+('{}'.format(I))+'.pdf'
        fig.savefig(route+name, fig)

然而,当我运行它时,我收到以下错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/dist-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 540, in runfile
    execfile(filename, namespace)
  File "/media/chidiac/My Passport/DOCUMENTS/My_Publications/2-3C273_radio_spectra/Maximum_flux_code.py", line 49, in <module>
    fig.set_yscale('log')
AttributeError: 'ErrorbarContainer' object has no attribute 'set_yscale'

我仍然是Python的初学者,我无法找到错误或如何解决错误。 非常感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

这篇文章可能有点旧,但是我遇到了同样的问题,也许这对未来的其他人有帮助。

您的初始解决方案实际上几乎是正确的。但是,set_yscale是轴的方法,而不是图。因此,if语句中的代码应如下所示:

import matplotlib.pyplot as plt

# other stuff you did ..

x=Q[:,1]
y=Q[:,2]
z=Q[:,3]
fig = plt.figure()
ax = plt.axes()
ax.set_xscale("log")
ax.set_yscale("log")
ax.errorbar(x,y,yerr=z, fmt = 'b')
ax.set_xlabel("Frequency")
ax.set_ylabel("Flux")
ax.set_title("Spectrum_{}.dat".format(I))
name="Spectrum_without_quiescent_{}.pdf".format(I)
plt.savefig(route+name)

我还调整了format功能的使用情况。

请注意,第二个解决方案无法始终正常运行。如果你有非常小的值和小的错误条,这些小值的对数将变大(例如log(10 ^( - 6))= -6,因为使用对数10的对数)并且你将有巨大的错误栏,尽管你的实际误差很小。

长话短说:使用ax.set_*scale。这很安全。

答案 1 :(得分:0)

我的一位朋友帮助我解决了这个问题,如果有人感兴趣,这就是解决方案:

route='/....../'
L=np.arange (1,59, 1)
print L 
for i in range (L.shape[0]):
    I=L[i]
    name_sq= 'Spectra_without_quiescent_'+('{}'.format(I))+'.dat' 
    Q=np.loadtxt(route+name_sq)
    if (len(Q) != 0):
        x=np.log(Q[:,1])
        y=np.log(Q[:,2])
        z=np.log(Q[:,3])
        fig, ax = plt.subplots(facecolor='w', edgecolor='k')
    plt.errorbar(x,y,yerr=z, fmt = 'b')
    plt.ylabel('Flux', size='x-large')
    plt.xlabel('Frequency', size='x-large')
    title='Spectrum_'+('{}'.format(I))+'.dat'
    name='Spectrum_without_quiescent_'+('{}'.format(I))+'.pdf'
    pylab.savefig(route+name)

第一个技巧是,首先获取数据的日志值,然后绘制它们。由于我不知道任何允许我在logscale中绘制错误栏的命令,我认为这是最好的解决方案。 第二个技巧是使用子图。否则,我在一个图中得到58条曲线,58次。

我希望这个解决方案很有帮助。