MatplotLib - 将查询结果分组为多个图

时间:2013-10-03 15:15:00

标签: python matplotlib

我有一个等同于

的查询
SELECT
     MONTH,
     TEAM,
     COUNT(*)
FROM
    TABLE

我打算使用Matplotlib绘制结果,在同一图表上为不同的TEAM值绘制单独的图。此字段的可能值事先未知。

分割从光标返回的列表的最佳方法是什么,以便它适合发送到pyplot?

1 个答案:

答案 0 :(得分:0)

这是 a 分割列表的方法。我不知道这是否是“拆分清单的最佳方法。”

def display(conn):
    cur = conn.cursor()
    cur.execute('select month, team, count(*) from events group by month, team')
    months = defaultdict(list)
    count = defaultdict(list)
    for row in cur:
        months[row[1]].append(int(row[0]))
        count[row[1]].append(int(row[2]))
    cur.close()
    for k in months:
        pylab.plot(months[k], count[k], label=k)
    pylab.legend()
    pylab.show()

完整的示例程序:

import sqlite3
import pylab
from collections import defaultdict

def populate_table(conn):
    with conn:
        conn.execute('create table events (month, team, value)')
        conn.executemany(
            'insert into events values (?,?,?)', (
                (1, 'Bluejays', 98.2),
                (1, 'Redbirds', 42),
                (1, 'Green Eggs and Ham', 1),
                (1, 'Bluejays', 98.2),
                (1, 'Redbirds', 42),
                (1, 'Bluejays', 98.2),
                (1, 'Green Eggs and Ham', 1),
                (2, 'Green Eggs and Ham', 98.2),
                (2, 'Redbirds', 42),
                (2, 'Green Eggs and Ham', 1),
                (2, 'Bluejays', 98.2),
                (2, 'Redbirds', 42),
                (2, 'Bluejays', 98.2),
                (2, 'Green Eggs and Ham', 1),
                (3, 'Green Eggs and Ham', 98.2),
                (3, 'Redbirds', 42),
                (3, 'Green Eggs and Ham', 1),
                (3, 'Bluejays', 98.2),
                (3, 'Redbirds', 42),
                (3, 'Redbirds', 98.2),
                (3, 'Green Eggs and Ham', 1)))

def display(conn):
    cur = conn.cursor()
    cur.execute('select month, team, count(*) from events group by month, team')
    months = defaultdict(list)
    count = defaultdict(list)
    for row in cur:
        months[row[1]].append(int(row[0]))
        count[row[1]].append(int(row[2]))
    cur.close()
    for k in months:
        pylab.plot(months[k], count[k], label=k)
    pylab.legend(loc="lower left")
    pylab.xlim(.5,3.5)
    pylab.xticks(range(1,4))
    pylab.ylim(.5,3.5)
    pylab.yticks(range(1,4))
    pylab.xlabel("Month")
    pylab.ylabel("Events")
    pylab.show()


conn = sqlite3.connect(':memory:')
populate_table(conn)
display(conn)

结果:

enter image description here