如何使用Gnuplot对字符串及其数据进行分组?

时间:2013-03-09 22:43:43

标签: gnuplot

我是Gnuplot的新手,希望能够绘制大量数据,如下所示:

Description violFine state
"Red Light Violation" $75.00 MD
"No Stop/Park Handicap" $502.00 MD
"Red Light Violation" $75.00 MD
"No Stop/Park Handicap" $502.00 MD
"Red Light Violation" $75.00 MD
"Red Light Violation" $75.00 MD
"Red Light Violation" $75.00 VA
"All Other Stopping or Parking Violations" $32.00 MD
"Red Light Violation" $75.00 MD
"Red Light Violation" $75.00 MD

如您所见,顶行是列的名称,“描述”列中有许多重复的字符串值。我想要做的是将每个唯一的“描述”中的所有“violFine”数字相加,并将其绘制在x轴上的“描述”和y轴上的“violFines”的总和上。我已经制作了一个图表来说明我在这个链接上可以访问的内容:http://i.imgur.com/NtZsZCR.jpg
(对不起,如果我有足够的声望点,我会在这个页面上提供它。)

任何有关此事的帮助都会很棒!谢谢!

1 个答案:

答案 0 :(得分:1)

这种数据处理任务不适合gnuplot。幸运的是,gnuplot很高兴让你使用其他工具来处理数据,然后将结果输入管道。在这里,我会使用python

from collections import defaultdict
import csv
import sys

d = defaultdict(list)
with open(sys.argv[1]) as fin:
    next(fin)  #remove the first line which doesn't contain data
    reader = csv.reader(fin,delimiter=' ',quotechar='"')
    for row in reader:
        d[row[0]].append(float(row[1][1:]))

for k,v in d.items():
    print '"{0}"'.format(k),sum(v)

现在在gnuplot中,您可以将其绘制为:

plot '< python script.py datafilename' using (column(0)):2:xtic(1) with lines