matplotlib: Insert comment on timeline graph

Inserting a comment into the time axis graph (ʻaxis.text () , ʻaxis.annotate ()) is specified by time on the target axis [^ 1].

[^ 1]: In the example below, the X axis is the time axis

comment.py


import sys
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.dates as dates
from datetime import datetime as dt
import pandas as pd

fig, ax = plt.subplots()
ax.xaxis_date()
ax.set_xlim([dt(2017,1,1),dt(2017,1,14)])
ax.set_ylim([0,100])
ax.grid(True)
ax.text(dt(2017,1,3,12,0), 53, "Datetime")
ax.text(pd.Timestamp("2017-1-5"), 40, "Pandas")
ax.text(736340, 70, "Number") #1

plt.xticks(rotation=45)
fig.subplots_adjust( bottom=0.15, top=0.95,left=0.1, right=0.95)
plt.savefig("comment.png ")

python


$ python comment.py

Either datetime or pd.Timestamp is fine.

comment.png

About the numerical value used for the time axis

Matplotlib provides sophisticated date plotting capabilities, standing on the shoulders of python datetime, the add-on modules pytz and dateutil. datetime objects are converted to floating point numbers which represent time in days since 0001-01-01 UTC, plus 1. For example, 0001-01-01, 06:00 is 1.25, not 0.25. The helper functions date2num(), num2date() and drange() are used to facilitate easy conversion to and from datetime and numeric ranges.

Source

That's right.

2016-12-31 00:00:00 (UTC) including leap years, let's roughly calculate,

python


$ perl -le '$a += ($_ % 4 == 0 and $_ % 100 == 0 and $_ % 400 != 0 )? 365 : $_ % 4 == 0 ? 366 : 365 for 1 .. 2016  ; print $a'
736329
$ python -c 'import matplotlib.dates as md ; print(md.num2date(736329))'
2016-12-31 00:00:00+00:00 

Will be. So, # 1 above is the same as specifying 2017-01-11 00: 00: 00 + 00.

For hours, minutes, and seconds, [^ 2] after the decimal point. [^ 2]: If it was 9:00:05, (9 * 60 * 60 + 5) / (24 * 60 * 60)

Recommended Posts

matplotlib: Insert comment on timeline graph
matplotlib graph album
Install matplotlib and display graph on Jupyter Notebook
Graph drawing using matplotlib
Band graph with matplotlib
Multiple file processing with Kivy + Matplotlib + Draw Graph on GUI
Create SVG graph with matplotlib on heroku (displayed in Japanese)
A comment on Boruta algorithm
Set matplotlib font on ubuntu
Graph drawing method with matplotlib
Graph Excel data with matplotlib (2)
Real-time graph display by matplotlib
View matplotlib plots on Tensorboard