Python 初心者 時系列のグラフを書く
ここからグラフの形をえらんで作れる: matplotlib を使う場合
グラフの例:Thumbnail gallery — Matplotlib 1.4.3 documentation
import MySQLdb
from pylab import *
import sys
import numpy as np
import matplotlib.pyplot as plt
import datetime
from matplotlib.dates import YearLocator, MonthLocator, DayLocator, DateFormatter
connection = MySQLdb.connect(host="localhost", db="agemono", user="root", passwd="password", charset="utf8")
cursor= connection.cursor()
query="select avg_sales+abs(avg_destruction), date from centerinvicinityd"
cursor.execute(query)
data = cursor.fetchall()
prod =
datestring=
for row in data:
prod.append(row[0])
print row[1]
dateeach = datetime.datetime.strptime(row[1], '%m/%d/%y')
datestring.append(dateeach)
axis([min(datestring), max(datestring), min(prod), max(prod)])
years = YearLocator() # every year
months = MonthLocator() # every month
monthsFmt = DateFormatter('%m')
days = DayLocator()
fig, ax = plt.subplots()
ax.plot_date(datestring, prod, '-')
ax.xaxis.set_major_locator(months)
ax.xaxis.set_major_formatter(monthsFmt)
ax.xaxis.set_minor_locator(days)
title(query)
grid(True)
plt.show()
cursor.close()
connection.close()
------------------------------------------
参考の例:
pylab_examples example code: date_demo1.py — Matplotlib 1.4.3 documentation
pylab_examples example code: date_demo2.py — Matplotlib 1.4.3 documentation
エラーメモ:
➜ matplotlib_test python avg_min_temp_prod.py
0
エラー:
Traceback (most recent call last):
File "avg_min_temp_prod.py", line 22, in <module>
datetime.datetime.strptime(date, '%m/%d/%Y')
TypeError: must be string, not list
=>
------------------
コード:
prod =
datestring=
for row in data:
prod.append(row[0])
dateeach = datetime.datetime.strptime(row[1], '%m/%d/%Y')
datestring.append(dateeach)
エラー:
ValueError: time data '1/1/14' does not match format '%m/%d/%Y'
原因:
01/01/14 とかにしないといけなかった
参考:
解決方法:
参考:
ーーーーーーーーーーーー参考サイト
You should be using datetime.datetime.strptime
. Note that very old versions of Python (2.4 and older) don't have datetime.datetime.strptime
; use time.strptime
in that case.
参考:
You must first convert your timestamps to python datetime
objects (use datetime.strptime
). Then use date2num
to convert the dates to matplotlib format.
Plot the dates and values using plot_date
:
dates = matplotlib.dates.date2num(list_of_datetimes)
plot_date(dates, values