如何在matplotlib中打印同一文本文件中的多组数据

2024-10-01 13:26:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我有数据文件,比如data.txtas

1 10 
2 20
3 30
4 41
5 49

1 11
2 19
3 32
4 37
5 52

注意有两组数据。我想把它们画在同一张图上。在gnuplot中,非常简单,我们只需运行plot 'data.txt' with line就可以得到这样的图, enter image description here

实际上我在同一个数据文件中有50个这样的集合。我刚开始学习python。我想用numpymatplotlib来绘制这个数据文件。在

在这个论坛里也有类似的帖子

How to plot data from multiple two column text files with legends in Matplotlib?

How can you plot data from a .txt file using matplotlib?

但我找不到与我的问题类似的东西。在


Tags: 数据fromnumpytxtdataplotmatplotlib数据文件
1条回答
网友
1楼 · 发布于 2024-10-01 13:26:31

一种方法是读取完整的文件,在出现双换行符的位置将其拆分,.split('\n\n'),并使用numpy.loadtxt读取每个部分。在

import numpy as np
from io import StringIO 
import matplotlib.pyplot as plt

filename="data.txt"
with open(filename) as f:
    data = f.read()

data = data.split('\n\n')

for d in data:
    ds = np.loadtxt(StringIO(unicode(d)))
    plt.plot(ds[:,0],ds[:,1])

plt.show()

相关问题 更多 >