Python:在循环中以对数对数比例绘制误差条,然后保存图像

use*_*144 3 python plot loglog errorbar

我有 58 个文件需要绘制。其中一些是空的(并不重要,我已经用 if 条件跳过了它们)。我需要使用对数刻度和误差线绘制文件中的数据。我想最后保存这些情节。我正在使用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)
Run Code Online (Sandbox Code Playgroud)

但是,当我运行它时,出现以下错误:

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'
Run Code Online (Sandbox Code Playgroud)

我仍然是Python的初学者,我找不到错误,或者如何修复它。非常感谢任何帮助。

Jul*_*ien 5

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

您最初的解决方案实际上几乎是正确的。然而,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)
Run Code Online (Sandbox Code Playgroud)

我还调整了您对该format功能的使用。

请注意,您的第二个解决方案并不总是能正常工作。如果你有非常小的值和小的误差条,这些小值的对数将变得很大(例如 log(10^(-6)) = -6,因为使用以 10 为底的对数)并且你将有巨大的误差条,尽管你的实际误差很小。

长话短说:使用ax.set_*scale. 它是安全的。