【问题标题】:Extra lines in plot when using matplotlib.plot使用 matplotlib.plot 时绘图中的额外线条
【发布时间】:2016-01-11 05:24:28
【问题描述】:

我正在尝试制作一个程序,该程序将根据包含 n*2 数值矩阵的给定文件创建一系列降序图(它们或多或少共享一个 x 轴,并且它们在y 轴,需要对其进行操作以避免重叠)。

现在,它的工作方式是使用 fileinput 一次读取一个文件,在第二列中的值中添加一个常数(只要常数分割每个图即可;我通过乘以数字来做到这一点文件的数量减 2,每个图减 2,因此它们被拆分),然后将操作值添加到两个主列表(用于 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()

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

【问题讨论】:

    标签: python numpy matplotlib plot


    【解决方案1】:

    尝试类似:

    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()
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-02
        • 2022-09-24
        • 1970-01-01
        • 2018-12-01
        相关资源
        最近更新 更多