-1

How can I use a date from a Sqlite database on the x-axis to make a bar graph with matplotlib?

If I convert the date to unix timestamp the graph works, but I would like to get something like this: https://i.stack.imgur.com/ouKBy.png

lowestNumber = self.c.execute('SELECT number,date, time FROM testDB ORDER BY number ASC LIMIT 1')
        for rows in lowestNumber:
            datesLow = rows[1]#returns 2016-02-23
            splitDate = datesLow.split('-' )
            spaces = ""
            # tabs = '/'
            # tabsDatesLow = tabs.join( splitDate )
            joinDatesLow = spaces.join( splitDate )

            x = int(joinDatesLow)

            plt.bar(x,low, label="Minimum number of players", color="red")
            plt.show()
Squexis
  • 97
  • 1
  • 4
  • 12

1 Answers1

1

You need to have an integer time format for plotting dates in matplotlib, and then a date formatting object is passed to format the axes. Matplotlib's date2num function can do this for you. Another good example is Matplotlib's documentation with an example here: http://matplotlib.org/examples/pylab_examples/date_demo1.html. Here is a solution yo may find useful:

import datetime
import matplotlib.pyplot as plt
from matplotlib.dates import AutoDateLocator, AutoDateFormatter, date2num

#make my own data:
date = '2016-02-23'
low = 10

#how to format dates:
date_datetime = datetime.datetime.strptime(date, '%Y-%m-%d')
int_date = date2num( date_datetime)

#create plots:
fig, ax = plt.subplots()

#plot data:
ax.bar(int_date,low, label="Minimum number of players", color="red")

#format date strings on xaxis:
locator = AutoDateLocator()
ax.xaxis.set_major_locator(locator)
ax.xaxis.set_major_formatter( AutoDateFormatter(locator) )

#adjust x limits and apply autoformatter fordisplay of dates
min_date = date2num( datetime.datetime.strptime('2016-02-16', '%Y-%m-%d') )
max_date = date2num( datetime.datetime.strptime('2016-02-28', '%Y-%m-%d') )
ax.set_xlim([min_date, max_date])
fig.autofmt_xdate()

#show plot: 
plt.show()
Lucas Currah
  • 418
  • 4
  • 8