Date into matplotlib graph

2024/9/19 14:28:55

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.sstatic.net/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-23splitDate = 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()
Answer

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()
https://en.xdnf.cn/q/119321.html

Related Q&A

Non blocking IO - Programming model

In non blocking IO programming model, a thread blocked on data available channels, as shown below, in python,while True:readers, _, _ = select.select([sys.stdin, sock], [], []) # blocked select()for re…

How to globally change xticks label relplot in Seaborn

I am facing an issue to globally changed the x-tick label for plot render using the relplot The idea was to change the int to string x-tick label for both plot. The desired label is [a,b,c,d] However, …

How to solve MatplotlibDeprecationWarning: scipy.stats.norm.pdf warning?

I am using matplotlib in my Python code. I got following warning: xxx.py:88: MatplotlibDeprecationWarning: scipy.stats.norm.pdfy = 100 * mlab.normpdf(bin_middles, mu, sigma)*bin_width I was wondering…

time data 42:53.700 does not match format %H:%M:%S.%f (match)

I am trying to convert a column in string format to DateTime format, However, I am getting the following error, could somebody please help? The error:time data 42:53.700 does not match format %H:%M:%S…

How can I import .py file? [duplicate]

This question already has answers here:Adding a directory to sys.path with pathlib(4 answers)Closed last year.Below is my code: from pathlib import Path import os import sys sys.path.insert(0, os.path.…

python: convenient way to create list of strings of repeated elements

How can I create a list like this:["a","a","a",... (repeating "a" a hundred times") "b","b","b",(repeating "b" a hun…

An accurate python sleep function

Ive tried time.sleep(), but its accuracy is total garbage. Consider this loop, for instance:for i in range(10000000):print(i)sleep(.334)Watch the numbers it prints. If its anything like my computer, it…

How to map python dictionary key values to each other?

Suppose we have two dictionaries as below: dict_a_to_b = {2:4, 6:9, 9:3} dict_a_to_c = {2: 0.1, 6:0.2, 9: 0.8}How to map these two dictionaries to make dict_c_to_b in python? dict_c_to_b = {0.1:4, 0.2…

Installing Keyrock on Fiware in my Virtual Machine

I want install keyrock and I follow these steps, but in the step three, when I write in the console:sudo python tools/install_venv.pyConsole shows me the next fail:Could you help me, please?

Cartopy error when attempting to plot rivers

When attempting to use Cartopy to plot rivers, Im getting a URL error. Im not even sure the rivers feature will plot what I want...Im attempting to get the Galveston Ship Channel to show on my map. Her…