使用 python 从 csv 文件绘制堆积条形图

plot stacked bar chart from csv file using python

我有来自 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

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

谁能帮帮我?我已经坚持了2天了!谢谢!

以下是我的解决方法:

  1. 读取 csv 文件。这可以使用 python
  2. csv 模块来完成
  3. 阅读 and/or 根据您的 bin 大小转换日期戳,并遍历每一行,添加到正确的小时 bin 中。我只是用肮脏的方式来做,并缩短了分钟和秒数:row[0][:-5] returns 15/07/2015 11,一个日期和时间。

你最终会得到一个列表 status_records,它包含两个字典,代表两个状态选项,然后包含小时箱:

  • "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()

输出:

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

无论如何,这应该会给你一些开始的东西。