2017-04-27 76 views
0

我有從SQL數據庫查詢派生直方圖。的代碼如下:matplotlib直方圖軸格式化

def histogram(self): 

    conn = sqlite3.connect('tooldatabase.db') 
    c = conn.cursor() 
    c.execute('PRAGMA foreign_keys = ON') 
    c.execute("SELECT evaluation from evaluations") 
    evaluations=c.fetchall() 
    print(evaluations) 
    minimum=min(evaluations, key = lambda t: t[0]) 
    maximum=max(evaluations, key = lambda t: t[0]) 
    print(minimum,maximum) 
    eval=[] 
    for (y,) in evaluations: 
     eval.append(y) 
    bin=[] 
    for x in range(1,maximum[0]+2): 
     bin.append(x) 

    figure=plt.figure(1) 
    plt.hist(eval,bins=bin, facecolor='blue',edgecolor='black',) 
    plt.xticks(bin, bin) 
    plt.xlabel('evaluation') 
    plt.ylabel('No of problems') 
    plt.title('Evaluations Distribution Histogram') 
    plt.show() 

的輸出如下所示: https://gyazo.com/d73b20a118db0088aab261c079613b00

我想將其顯示爲: https://gyazo.com/063990cd8741682f45b5a37ba594ff56

當x軸的數字是向右偏移側多一點。有沒有辦法做到這一點?

+1

的可能的複製[Matplotlib xticks不排隊與直方圖(http://stackoverflow.com/questions/27083051/ – DavidG

回答

2

我認爲你必須修改xticks位置,如:

import matplotlib.pyplot as plt 
import numpy as np 

# test data 
eval = np.random.randint(0,3,10) 
bin = np.arange(4) # len + 1 

figure=plt.figure(1) 
plt.hist(eval,bins=bin, facecolor='blue',edgecolor='black') 
# shift ticks by .5 
plt.xticks(bin-.5, bin) 
plt.xlabel('evaluation') 
plt.ylabel('No of problems') 
plt.title('Evaluations Distribution Histogram') 
plt.show() 

enter image description here

+0

plt.xticks(bin-.5,bin) TypeError:不支持的操作數類型爲 - :'list'和'float' – DynamicQ

+1

嘗試'plt。 xticks(np.array(bin) - 。5,bin)'。 – Serenity

+0

工程。非常感謝你 – DynamicQ