【问题标题】:How to plot multiple set of data from same text file in matplotlib如何在 matplotlib 中绘制来自同一文本文件的多组数据
【发布时间】:2017-10-10 09:22:53
【问题描述】:

我有数据文件说data.txt

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,我们就会得到这样的图表,

实际上我在同一个数据文件中有 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?

但我找不到与我的问题相似的任何内容。

【问题讨论】:

  • 你能展示你拥有的代码吗?

标签: python numpy matplotlib plot


【解决方案1】:

一个想法可以是读取整个文件,在出现双换行符的位置将其拆分,.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()

【讨论】:

  • unicode 在使用 python3 运行时出现 NameError,因为 Python 3unicode 类型重命名为 str。将其替换为str 后,它起作用了,感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 2018-11-28
  • 2017-01-10
  • 2012-06-30
  • 1970-01-01
  • 1970-01-01
  • 2020-10-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多