通过图形标签迭代

时间:2013-01-04 12:56:52

标签: python mongodb matplotlib

我正在绘制一个有几行的图表,并希望为每一行分配一个特定的标签,该标签将在图例中显示。

这为每一行提供了相同的标签:

import pylab as P
connection = pymongo.Connection("mongodb://localhost", safe=True)
db = connection.stuff
data = stuff.collection

for i in data.find():
    a=[]
    for element in i["counts"]:
        a.append(element["total"])
    P.plot(a, label="first line")
    P.legend()

P.show()

我有很多数据,我的文档以这种方式构建:

{name:..., data:..., counts:[{total:...,...},{total:...,...}]}

如何为该代码段中的每一行分配不同的标签? 谢谢!

1 个答案:

答案 0 :(得分:1)

如果您想从数据中获取属性,可以采用以下方式:

for i in data.find():
    a=[]
    somename = i["name"][??]        #maybe you can extract your label from here ?
    for element in i["counts"]:
        a.append(element["total"])
    P.plot(a, label=somename)       # and use it here
P.legend()
P.show()

此外,在所有绘图完成后,您应该只调用legend()一次。

虽然与您的问题无关,但请注意您也可以通过以下方式构建列表:

for i in data.find():
    a = [element['total'] for element in i['counts']]
    P.plot(a, label=somename)
P.legend()
P.show() 
相关问题