DynamicQ
DynamicQ

Reputation: 135

matplotlib histogram axis formatting

I have a histogram from derived from an sql database query. The code is as follows:

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()

The output is as follows: https://gyazo.com/d73b20a118db0088aab261c079613b00

I would like to display it as: https://gyazo.com/063990cd8741682f45b5a37ba594ff56

Where the x-axis numbers are shifted to the right side a bit more. Is there a way possible to do this?

Upvotes: 1

Views: 15101

Answers (1)

Serenity
Serenity

Reputation: 36635

I think you have to modify xticks position like:

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

Upvotes: 7

Related Questions