2017-04-01 28 views
-1

私が始め始める前に、私はスタックオーバーフローが新しく、質問の形式が間違っていたら謝ります。また、これは私の学校図書館のためのAレベルの学校プロジェクトのためのもので、図書館の管理を手助けすることを目的としています。 「pastLoans」(see here)という名前の学生の前回の融資に関するデータを含む表を作成しました。図書館ユーザーの中で最も人気のある図書を見つけ、その結果を棒グラフで表現する方法が必要です。これを行うために、私は現在、私はそこに2冊の本(see here)を持って、 'pastLoans'テーブルの 'ブック'欄から書籍のタイトルが表示される回数をカウントするSQLコマンドを作成しました。Python:SQlite3データベースのデータを使ってTkinterに棒グラフを作成する

Tk.canvas棒グラフの性質はそれぞれデータとしての整数だけであるため、本の名前とその量を使ってテーブル内で発生する時間の量を分割する方法を見つける必要がありますそれがbarchartに表示されるデータとして発生した回数と、X軸上のラベルとしてブックの名前を返します。

現在、私は、SQLite3の 'COUNT'機能を使用して過去のローンに関するデータを含むテーブルから必要なデータを引き出すためにSQLコマンドをコーディングしました。さらに、棒グラフのフレームをコーディングし、例えば、[1,2,3,4,5、..]のサンプルデータで

棒グラフが正しいデータ値でTkinterに正常に表示されることに注意してください。残念ながら私は結果の画像を追加できません私は十分な担当者がいません。

は私のコードは次のようになります。

command = ("SELECT book,COUNT(book) AS cnt FROM pastLoans GROUP BY 
    book ORDER BY cnt DESC;") 

    c.execute(command) 
    result = c.fetchall() 
    print (result)        
    """This is the code for pulling the book name and amount of books 
    from the "pastLoans" as well as the book name, the result is this: 

    >>> [('Book', 1), ('Harry Potter', 1)] 


    This is my bar chart frame:""" 

    data = [1, 2, 3, 4, 5] #The data used here is sample data. 

    g_width = 900 # Define it's width 
    g_height = 400 # Define it's height 
    g = tk.Canvas(self, width=g_width, height=g_height) 
    g.grid() 

    # The variables below size the bar graph 
    y_stretch = 15 # The highest y = max_data_value * y_stretch 
    y_gap = 20 # The gap between lower canvas edge and x axis 
    x_stretch = 10 # Stretch x wide enough to fit the variables 
    x_width = 20 # The width of the x-axis 
    x_gap = 20 # The gap between left canvas edge and y axis 

    for x, y in enumerate(data): 

     # coordinates of each bar 

     # Bottom left coordinate 
     x0 = x * x_stretch + x * x_width + x_gap 

     # Top left coordinates 
     y0 = g_height - (y * y_stretch + y_gap) 

     # Bottom right coordinates 
     x1 = x * x_stretch + x * x_width + x_width + x_gap 

     # Top right coordinates 
     y1 = g_height - y_gap 

     # Draw the bar 
     g.create_rectangle(x0, y0, x1, y1, fill="red") 

     # Put the y value above the bar 
     g.create_text(x0 + 2, y0, anchor=tk.SW, text=str(y)) 
+0

私はあなたの問題をかなり得ていません。あなたは 'str(y)'の代わりに書籍のタイトルを追加したいと思うかもしれませんが、あなたはresultのエントリーをどのように反復するのか分かりません。 – BurningKarl

+0

本の名前(文字列)と本が出現する回数(整数)を分けて、本の名前とX軸とその本がYに出現する回数をプロットする軸。 – SadfSadv

答えて

0

あなたはすでにすべての作業を行っているとして、あなただけのresultの代わりdataを反復する必要がバーとその上のいくつかのテキストを表示Tkinterを取得する:

# Sort so that the most popular book is on the left 
result.sort(key=lambda e: e[1], reverse=True) 

for x, (name, y) in enumerate(result): 
    ... 

    # Put the name above the bar 
    g.create_text(x0 + 2, y0, anchor=tk.SW, text=name) 

x_stretch変数を変更して、テキストが重ならないようにする必要があります。

関連する問題