Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to skip empty dates (weekends) in a financial Matplotlib Python graph?

ax.plot_date((dates, dates), (highs, lows), '-')

I'm currently using this command to plot financial highs and lows using Matplotlib. It works great, but how do I remove the blank spaces in the x-axis left by days without market data, such as weekends and holidays?

I have lists of dates, highs, lows, closes and opens. I can't find any examples of creating a graph with an x-axis that show dates but doesn't enforce a constant scale.

like image 598
Eric the Red Avatar asked Aug 13 '09 17:08

Eric the Red


People also ask

Is PLT show () needed?

Using plt. show() in Matplotlib mode is not required.

What are backends matplotlib?

Matplotlib is a plotting library. It relies on some backend to actually render the plots. The default backend is the agg backend. This backend only renders PNGs. On Jupyter notebooks the matplotlib backends are special as they are rendered to the browser.

Can matplotlib plot real time graphs in Python?

To create a real-time plot, we need to use the animation module in matplotlib. We set up the figure and axes in the usual way, but we draw directly to the axes, ax , when we want to create a new frame in the animation.


3 Answers

One of the advertised features of scikits.timeseries is "Create time series plots with intelligently spaced axis labels".

You can see some example plots here. In the first example (shown below) the 'business' frequency is used for the data, which automatically excludes holidays and weekends and the like. It also masks missing data points, which you see as gaps in this plot, rather than linearly interpolating them.

alt text

like image 57
Autoplectic Avatar answered Nov 06 '22 00:11

Autoplectic


I think you need to "artificially synthesize" the exact form of plot you want by using xticks to set the tick labels to the strings representing the dates (of course placing the ticks at equispaced intervals even though the dates you're representing aren't equispaced) and then using a plain plot.

like image 40
Alex Martelli Avatar answered Nov 05 '22 23:11

Alex Martelli


Up to date answer (2018) with Matplotlib 2.1.2, Python 2.7.12

The function equidate_ax handles everything you need for a simple date x-axis with equidistant spacing of data points. Realised with ticker.FuncFormatter based on this example.

from __future__ import division
from matplotlib import pyplot as plt
from matplotlib.ticker import FuncFormatter
import numpy as np
import datetime


def equidate_ax(fig, ax, dates, fmt="%Y-%m-%d", label="Date"):
    """
    Sets all relevant parameters for an equidistant date-x-axis.
    Tick Locators are not affected (set automatically)

    Args:
        fig: pyplot.figure instance
        ax: pyplot.axis instance (target axis)
        dates: iterable of datetime.date or datetime.datetime instances
        fmt: Display format of dates
        label: x-axis label
    Returns:
        None

    """    
    N = len(dates)
    def format_date(index, pos):
        index = np.clip(int(index + 0.5), 0, N - 1)
        return dates[index].strftime(fmt)
    ax.xaxis.set_major_formatter(FuncFormatter(format_date))
    ax.set_xlabel(label)
    fig.autofmt_xdate()


#
# Some test data (with python dates)
#
dates = [datetime.datetime(year, month, day) for year, month, day in [
    (2018,2,1), (2018,2,2), (2018,2,5), (2018,2,6), (2018,2,7), (2018,2,28)
]]
y = np.arange(6)


# Create plots. Left plot is default with a gap
fig, [ax1, ax2] = plt.subplots(1, 2)
ax1.plot(dates, y, 'o-')
ax1.set_title("Default")
ax1.set_xlabel("Date")


# Right plot will show equidistant series
# x-axis must be the indices of your dates-list
x = np.arange(len(dates))
ax2.plot(x, y, 'o-')
ax2.set_title("Equidistant Placement")
equidate_ax(fig, ax2, dates)

Comparison of default plotting method and equidistant x-axis

like image 7
ascripter Avatar answered Nov 05 '22 22:11

ascripter