我有以下问题。我有一个由N个对组成的2D数组。例如:x= [5,2,10,5,3,2,...](所以一组数组a= 5,10,3,...和b= 2,5,2,...第一列(a)对应于项目的数量。第二栏(b)是获取(a)栏中的项目所需的时间。
我想绘制获取项目所用总时间的累积直方图。X轴将位于数组(a)的仓位中,y轴应为(a)的每个仓位的来自数组(b)的时间总和。例如,我想绘制"Nr of items"-vs-"Total time to obtain (cumulative)“,而不是默认的"Nr of items"-vs-"Nr of instances in array (a)”。
我希望这是有意义的。
发布于 2010-11-25 02:03:59
这些天来,我往往是matplotlib (http://matplotlib.sourceforge.net/)的铁杆粉丝。它有很多内置的功能,几乎所有你想要做的绘图类型。
这里有一大堆关于如何创建直方图的例子(有可用的图像和源代码):
http://matplotlib.sourceforge.net/examples/pylab_examples/histogram_demo_extended.html
下面是hist()函数本身的文档:
http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.hist
如果这不是您想要的,您可以浏览图库并寻找更适合的绘图类型。它们都有可用的源代码:
http://matplotlib.sourceforge.net/gallery.html
希望这就是你要找的。
添加一个示例。那么这是不是更符合你的要求呢?(实际上不再是直方图):

如果是这样,下面是生成它的代码(x是示例输入):
from pylab import *
x = [[5,2],[10,5],[3,2],[5,99],[10,22],[3,15],[4,30]]
a,b = zip(*x) #Unzip x into a & b as per your example
#Make a dictionary where the key is the item from a and the value
#is the sum of all the corresponding entries in b
sums = {}
for i in range(0,len(a)):
sums[a[i]] = b[i] if not a[i] in sums else sums[a[i]] + b[i]
#Plot it
ylabel('Bins')
xlabel('Total Times')
barh(sums.keys(),sums.values(),align='center')
show()如果不是,我会放弃,并承认我仍然不太明白你想要什么。祝好运!
发布于 2010-11-25 02:58:48
有没有可能这就是你所说的?
>>> pairs = [[5,2],[10,5],[3,2]]
>>> a, b = zip(*pairs)
>>> x = list(a)
>>> y = [reduce(lambda c, d: c+d, b[:i], 0) for i in range(1, len(b)+1)]
>>> x
[5, 10, 3]
>>> y
[2, 7, 9]这里得到的y值是从b到该索引的所有值的总和。
发布于 2010-11-25 02:40:16
我不确定这是你想要的..。
x = [[5,2],[10,5],[3,2]]
a,b=zip(*x) #(5, 10, 3),(2, 5, 2)
tmp = []
for i in range(len(a)):
tmp.extend(b[i:i+1]*a[i]) #[2, 2, 2, 2, 2, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 2, 2, 2]
def cum(l):
c=0
for i in range(len(l)):
c+=l[i]
yield c
y=list(cum(tmp)) #[2, 4, 6, 8, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 62, 64, 66]
list(zip(range(1,1+len(y)),y)) #[(1, 2), (2, 4), (3, 6), (4, 8), (5, 10), (6, 15), (7, 20), (8, 25), (9, 30), (10, 35), (11, 40), (12, 45), (13, 50), (14, 55), (15, 60), (16, 62), (17, 64), (18, 66)] https://stackoverflow.com/questions/4269929
复制相似问题