使用matplotlib.plot时绘图中的额外线条

时间:2016-01-10 20:56:50

标签: python numpy matplotlib plot

我试图制作一个程序,根据包含n * 2数值矩阵的给定文件创建一系列下降图(它们或多或少共用一个x轴,它们'在y轴上足够接近它们需要被操纵以避免重叠。)

现在,它的工作方式是使用fileinput一次读入一个文件,为第二列中的值添加一个常量(任意,只要常量分割每个绘图;我通过乘以数字来实现两个文件的数量减少,每个图减少两个,所以它们被分割),然后将操纵值添加到两个主列表(对于x和y),最后由matplotlib绘制。

我让它非常接近我想要的东西,但它有一些奇怪的线条将一个文件的末尾连接到下一个文件的开头,我想知道如何删除它们。

以下是代码的相关部分:

mpl.suptitle(spectitle, fontsize=16)
mpl.xlabel('wavelength (A)', fontsize=14)
mpl.ylabel('flux (erg s^-1 cm^-2)', fontsize=14)

with open(filelist) as infile:
    allfiles = [line.rstrip('\n') for line in open(filelist)]

multiplier = len(allfiles)
multiplier *= 2

for line in fileinput.input(allfiles):
    filename = fileinput.filename()
    waveN, fluxN = np.loadtxt(filename, usecols=[0,1], unpack=True)
    fluxCalc = np.array(fluxN)
    fluxCalc += multiplier
    multiplier -= 2 #decrease multiplier, causing next output specturm to be placed below the one just calculated
    wavelenAll.extend(waveN)
    fluxCalc.tolist()
    fluxAll.extend(fluxCalc)
    fileinput.nextfile()

mpl.plot(wavelenAll, fluxAll)
mpl.savefig('allspec.png')
mpl.show()

我可以在几个小时内添加输出图像。感谢您提前提供任何帮助。

2 个答案:

答案 0 :(得分:2)

尝试类似:

import matplotlib.pyplot as plt
import numpy as np

filelist = []
spectitle = 'spectrum'

with open(filelist) as infile:
    allfiles = [line.rstrip('\n') for line in open(filelist)]

all_flux, all_wavelen = [], []

# just get the data from the file and accumulate in a list
# which assumes you want these lists for something else
for fname in allfiles:
    waveN, fluxN = np.loadtxt(fname, usecols=[0, 1], unpack=True)
    all_flux.append(fluxN)
    all_wavelen.append(waveN)


fig, ax = plt.subplots()

fig.suptitle(spectitle, fontsize=16)
ax.set_xlabel('wavelength (A)', fontsize=14)
ax.set_ylabel('flux (erg s^-1 cm^-2)', fontsize=14)
# loop over the data and plot
for wv, flux, shift in zip(all_wavelen, all_flux,
                           range(1, len(allfiles) + 1)[::-1]):
    # do the shift as late as possible so you do not accidentally reuse
    # cosmetically shifted data for computing something
    ax.plot(wv, flux + shift, color='b')

fig.savefig('allspec.png')
plt.show()

答案 1 :(得分:0)

它必须在数据中或由错误的后处理引起。除非我们看到数据,否则很难说更多。尝试在没有最后一个元素的情况下绘制它,例如像mpl.plot(wavelenAll[1:-1], fluxAll[1:-1])