gpt4 book ai didi

python - 使用 matplotlib.plot 时绘图中出现额外线条

转载 作者:行者123 更新时间:2023-12-01 04:12:33 25 4
gpt4 key购买 nike

我正在尝试制作一个程序,该程序将根据包含 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()

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

最佳答案

尝试如下:

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

关于python - 使用 matplotlib.plot 时绘图中出现额外线条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34710673/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com