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

PyRsquared

我有一个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_time1小时的垃圾箱的关系由于有几个不同的exit_status代码,因此我需要以堆叠的条形图的形式对其进行绘制,其中每个不同的退出状态都被赋予了不同的颜色。

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

阿德里安努斯

这是我要解决的方法:

  1. 读取csv文件。这可以使用csvpython模块来完成
  2. 根据您的垃圾箱大小阅读和/或转换日期戳,并遍历每行,添加到正确的小时箱中。我只是以一种肮脏的方式进行操作,并缩短了分钟和秒钟:row[0][:-5]return 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中排序,否则您必须在代码中自行对日期进行排序。

无论如何,这应该给您一些开始。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章