使用python绘制来自csv文件的堆积条形图

时间:2015-07-15 14:28:06

标签: python csv plot bar-chart stacked-chart

我有来自csv文件的数据,如下所示:

,jobID,hum_starttime,hum_endtime,duration,exit_status,CPU,energy,memory,virt_mem,wall_time
0,525231,29/05/2015 11:53:47,29/05/2015 14:09:16,8129.0,0.0,28:54:56,0,4682480kb,16036608kb,01:13:59
1,504231,08/05/2015 07:46:59,08/05/2015 07:48:55,116.0,0.0,00:00:49,0,2421756kb,2807020kb,00:00:51

我想在1小时的分档中绘制exit_status计数(即exit_status == 1exit_status == -11)与start_time的次数。由于有几个不同的exit_status代码,我需要以stacked bar chart的形式绘制它,其中每个不同的退出状态都被赋予不同的颜色。

任何人都可以帮助我吗?我已经坚持了2天!!谢谢!

1 个答案:

答案 0 :(得分:1)

以下是我将如何解决它:

  1. 阅读csv文件。这可以使用csv模块for python
  2. 来完成
  3. 根据您的箱子大小读取和/或转换日期戳,并遍历每一行,添加到正确的小时箱。我只是以肮脏的方式做,并减少分钟和秒:row[0][:-5]返回15/07/2015 11,一个日期和小时可以使用。
  4. 你最终得到一个列表status_records,它由两个dicts组成,代表两个状态选项,然后包含小时箱:

    • "1" : {"15/07/2015 11": 3, ...}
    • "-11" : {"15/07/2015 11": 0, ...}

    以下是一个示例data.csv,其中包含更多数据(这样您实际上可以看到某些内容,这对于您的2个条目来说很难 - 我使用相同的日期格式和你提到的状态代码):

    start_time,exit_status
    15/07/2015 11:53:47,1
    15/07/2015 11:53:47,1
    15/07/2015 11:54:56,1
    15/07/2015 12:23:26,-11
    15/07/2015 12:27:31,1
    15/07/2015 14:01:47,-11
    15/07/2015 14:11:56,1
    15/07/2015 14:52:47,1
    15/07/2015 15:53:23,1
    15/07/2015 15:55:11,1
    

    这是我的代码(您必须将row[0]等更改为相应的行以使用您的csv):

    #!/usr/bin/env python
    import numpy as np
    import matplotlib.pyplot as plt
    import csv
    
    # 1. reading the csv
    status_records = {'1': {}, '-11': {}}
    
    with open('data.csv', 'rb') as csvfile:
        reader = csv.reader(csvfile)
        # 2. iterate through csv
        for row in reader:
            if row[0] == 'start_time': continue # first line
            hour = row[0][:-5]
            status = row[1]
    
            # if hour not present, add empty 'slot' in each status bin
            if hour not in status_records[status].keys():
                status_records['1'][hour] = 0
                status_records['-11'][hour] = 0
                status_records[status][hour] = 1 # add the status we just read
            else:
                status_records[status][hour] += 1 # update status-hour bin
    
    status1   = status_records['1'].values()
    status2 = status_records['-11'].values()
    
    print status1, status2
    
    N = len(status1)
    ind = np.arange(N)
    width = 0.35
    
    p1 = plt.bar(ind, status1, width, color='g')
    p2 = plt.bar(ind, status2, width, color='r', bottom=status1)
    
    plt.ylabel('# of exit status')
    plt.title('Exit status in comparison with time')
    plt.yticks(np.arange(0,11,10))
    plt.legend((p1[0], p2[0]), ('1', '-11'))
    plt.show()
    

    输出:

    graph

    改进:您可能想要添加一些有用的标签,并决定是否显示没有任何反应的时间(这可能会使图表与间隙混乱)。另外,请注意,日期应该在csv中排序,否则你必须在代码中自己排序。

    无论如何,这应该给你一些东西。

相关问题