【问题标题】:How to plot a graph based on a txt file and split data by words?如何根据 txt 文件绘制图形并按单词拆分数据?
【发布时间】:2015-03-09 13:11:07
【问题描述】:

我的输出 txt 文件的单行看起来像:

   1          open       0   heartbeat       0      closed       0  

数据之间的差距是随机混合不同数量的 \t 和空间。 我写了一些类似

的代码
import numpy as np
import matplotlib.pyplot as plt

with open("../testResults/star-6.txt") as f:
    data = f.read()
data = data.split('\n')

x = [row.split'HOW?')[0] for row in data]
y = [row.split('HOW?')[8] for row in data]

fig = plt.figure()

ax1 = fig.add_subplot(111)

ax1.set_title("diagram")    
ax1.set_xlabel('x')
ax1.set_ylabel('y')

ax1.plot(x,y, c='r', label='the data')

leg = ax1.legend()

plt.show()

这显然行不通。无论如何我可以做一些 row.spilit_by_word 吗?

感谢您的帮助!谢谢..

【问题讨论】:

  • 您可能想要更改问题的标题和标签,因为它与 matplotlib 并没有真正的关系,而是与 python 中的基本字符串操作有关

标签: arrays numpy matplotlib text-files


【解决方案1】:

使用pandas。给定这个数据文件(我称之为“test.csv”):

   1          open       0   heartbeat       8      closed       0
  2          Open       1   h1artbeat       7      losed       10
   3        oPen       0   he2rtbeat       6      cosed       100
   4          opEn     1   hea3tbeat       5      clsed       10000
   5          opeN       0   hear4beat       4      cloed       10000
   6          OPen       1  heart5eat       3      closd       20000
   7          OpEn       0   heartb6at    2      close       2000
   8          OpeN       1   heartbe7t       1    osed       200
   9          oPEn       0   heartbea8       0   lsed       20

你可以这样做:

import pandas as pd

df=pd.read_csv('test.csv', sep='\s+', header=False)
df.columns=['x',1,2,3,4,5,'y']

x=df['x']
y=df['y']

其余的都一样。

你也可以这样做:

ax = df.plot(x='x', y='y', title='diagram')

ax1.set_xlabel('x')
ax1.set_ylabel('y')

plt.show()

【讨论】:

    【解决方案2】:

    最简单的方法是先将\t字符替换为空格,然后在空格上分割:

    row.replace('\t',' ').split()
    

    否则(例如,如果您有更多类型的分隔符或很长的行)使用re 可能会更好:

    re.split('\s*', row)
    

    显然你需要先做import re

    【讨论】:

      【解决方案3】:

      很难确定哪个是最佳答案,因为@TheBlackCat 给出了更具体的答案,而且看起来更简单,然后直接使用 matplotlib 我认为他的答案对于像我这样的初学者会更好,因为他们将来会看到这个问题。 然而,根据@hitzg 的建议,我制定了我的源代码以供分享。

      import numpy as np
      import matplotlib.pyplot as plt
      
      
      filelist = ["mesh-10","line-10","ring-10","star-10","tree-10","tri-graph-10"]
      fig = plt.figure()
      for filename in filelist:
          with open("../testResults/%s.log" %filename) as f:
              data = f.read()
          data = data.replace('\t',' ')
          rows = data.split('\n')
          rows = [row.split() for row in rows]
      
          x_arr = []
          y_arr = []
          for row in rows:
              if row:  #important : santitize null rows -> cause error
                  x = float(row[0])/10
                  y = float(row[8])
                  x_arr.append(x)
                  y_arr.append(y)
      
          ax1 = fig.add_subplot(111)
      
          ax1.set_title("result of all topologies")    
          ax1.set_xlabel('time in sec')
          ax1.set_xlim([0,30]) #set x axis limitation
          ax1.set_ylabel('num of mydist msg')
      
          ax1.plot(x_arr,y_arr, c=np.random.rand(4,1), label=filename)
      
          leg = ax1.legend()
      
      plt.show()
      

      希望它有所帮助,非常感谢 @TheBlackCat 和 @hitzg,向 matplotlib 新手并试图找到答案的人们致以最良好的祝愿:)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-07
        • 2023-01-25
        • 1970-01-01
        • 1970-01-01
        • 2023-03-15
        • 2016-07-22
        相关资源
        最近更新 更多