Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add date tickers to a matplotlib/python chart

I have a question that sounds simple but it's driving me mad for some days. I have a historical time series closed in two lists: the first list is containing prices, let's say P = [1, 1.5, 1.3 ...] while the second list is containing the related dates, let's say D = [01/01/2010, 02/01/2010...]. What I would like to do is to plot SOME of these dates (when I say "some" is because the "best" result I got so far is to show all of them as tickers, so creating a black cloud of unreadable data in the x-axis) that, when you zoom in, are shown more in details. This picture is now having the progressive automated range made by Matplotlib:

Zoom-out

Instead of 0, 200, 400 etc. I would like to have the dates values that are related to the data-point plotted. Moreover, when I zoom-in I get the following:

Zoom-in

As well as I get the detail between 0 and 200 (20, 40 etc.) I would like to get the dates attached to the list. I'm sure this is a simple problem to solve but I'm new to Matplotlib as well as to Python and any hint would be appreciated. Thanks in advance

like image 448
Matteo NNZ Avatar asked Jan 14 '14 07:01

Matteo NNZ


2 Answers

Matplotlib has sophisticated support for plotting dates. I'd recommend the use of AutoDateFormatter and AutoDateLocator. They are even locale-specific, so they choose month-names according to your locale.

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

xtick_locator = AutoDateLocator()
xtick_formatter = AutoDateFormatter(xtick_locator)

ax = plt.axes()
ax.xaxis.set_major_locator(xtick_locator)
ax.xaxis.set_major_formatter(xtick_formatter)

EDIT

For use with multiple subplots, use multiple locator/formatter pairs:

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

x = [datetime.datetime.now() + datetime.timedelta(days=30*i) for i in range(20)]
y = np.random.random((20))

xtick_locator = AutoDateLocator()
xtick_formatter = AutoDateFormatter(xtick_locator)

for i in range(4):
    ax = plt.subplot(2,2,i+1)
    ax.xaxis.set_major_locator(xtick_locator)
    ax.xaxis.set_major_formatter(xtick_formatter)
    ax.plot(date2num(x),y)


plt.show()
like image 131
Thorsten Kranz Avatar answered Sep 30 '22 18:09

Thorsten Kranz


You can do timeseries plot with pandas For detail refer this : http://pandas.pydata.org/pandas-docs/dev/timeseries.html and http://pandas.pydata.org/pandas-docs/dev/generated/pandas.Series.plot.html

import pandas as pd    
DateStrList = ['01/01/2010','02/01/2010']
P = [2,3]
D = pd.Series([pd.to_datetime(date) for date in DateStrList])
series =pd.Series(P, index=D)
pd.Series.plot(series)
like image 31
bistaumanga Avatar answered Sep 30 '22 19:09

bistaumanga