0

我有一个相当于的查询

SELECT
     MONTH,
     TEAM,
     COUNT(*)
FROM
    TABLE

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

拆分从光标返回的列表以使其适合发送到 pyplot 的最佳方法是什么?

4

1 回答 1

0

这是一种拆分列表的方法。我不知道这是否是“拆分列表的最佳方式”。

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)

结果:

在此处输入图像描述

于 2013-10-05T00:05:47.027 回答