DigitalOcean Referral Badge
Udit Vashisht
Author: Udit Vashisht


Plot Time Series in Python | Matplotlib Tutorial | Chapter 8

  • 7 minutes read
  • 57386 Views
Plot Time Series in Python | Matplotlib Tutorial | Chapter 8

    Table of Contents

Plot Time Series data in Python using Matplotlib

In this tutorial we will learn to create a scatter plot of time series data in Python using matplotlib.pyplot.plot_date(). We will use Pandas Dataframe to extract the time series data from a CSV file using pandas.read_csv().

The syntax and the parameters of matplotlib.pyplot.plot_date()

The syntax for plt.plot_date() is :-

matplotlib.pyplot.plot_date(x, y, fmt='o', tz=None, xdate=True, ydate=False, *, data=None, **kwargs)

and it returns a list of Line2D objects representing the plotted data.

The parameters of matplotlib.pyplot.plot_date() are shown in the table below:-

# Parameter Type Description
1 x,y array-like The coordinates of the data points. If xdate or ydate is True, the respective values x or y are interpreted as Matplotlib dates.
2 fmt str, optional The plot format string. For details, see the corresponding parameter in plot.
3 tz [ None | timezone string | tzinfo instance] The time zone to use in labeling dates. If None, defaults to rcParam timezone.
4 xdate bool, optional, default: True If True, the x-axis will be interpreted as Matplotlib dates.
5 ydate bool, optional, default: False If True, the y-axis will be interpreted as Matplotlib dates.

Creating a scatter plot from time series data in Python Matplotlib

First of all, we will create a scatter plot of dates and values in Matplotlib using plt.plot_date(). We will be using Python’s built-in module called datetime(datetime, timedelta) for parsing the dates. So, let us create a python file called ‘plot_time_series.py’ and make necessary imports.

We will be using seaborn style to create scatter plot of the time series data. Finally, we will be passing dates and values to plt.plot_date() method and call plt.show() to plot.

# plot_time_series.py

import matplotlib.pyplot as plt
from datetime import datetime, timedelta
plt.style.use('seaborn')

dates = [
    datetime(2019, 8, 21),
    datetime(2019, 8, 22),
    datetime(2019, 8, 23),
    datetime(2019, 8, 24),
    datetime(2019, 8, 25),
    datetime(2019, 8, 26),
    datetime(2019, 8, 27),
]

y = [0, 1, 2, 3, 4, 5, 6]

plt.plot_date(dates, y)
plt.tight_layout()
plt.show()

This will create a simple scatter plot for the time series data.

plot time series python_.png

Creating a line plot from time series data in Python Matplotlib

If we want to create a line plot instead of the scatter plot, we will have to set linestyle=’solid’ in plt.plot_date(). We can also change the markers.

# plot_time_series.py

plt.plot_date(dates, y, linestyle ='solid')

Aligning date ticks labels in Matplotlib

Sometimes, we are working with a lot of dates and showing them horizontally won’t be a good idea in that case. So, we can also change the alignment of the dates on x-axis of time series plot by using autofmt_xdate() on plt.gcf().

# plot_time_series.py

plt.gcf().autofmt_xdate

plot time series_python_.png

Formatting dates in Time Series plots in Matplotlib using Python

We will be formatting the date in our time series plot by using dates from matplotlib. We will be passing a python format string , as we would have passed to strftime to format the date in our time series plot.

So, I will be using matplotlib.dates.DateFormatter to format the date in DD-MM-YYYY and then pass it to set_major_formatter() method of matplotlib.pyplot.gca().

# plot_time_series.py

date_format = mpl_dates.DateFormatter('%d-%m-%Y')
plt.gca().xaxis.set_major_formatter(date_format)

plot time_series_python_.png

Plotting time series data in Python from a CSV File

Currently, we were using hard-fed example data to plot the time series. Now we will be grabbing a real csv file of bitcoin prices from here and then create a time series plot from that CSV file in Python using Matplotlib. So, now we have the time series data in CSV file called ‘plot_time_series.csv’. Let us plot this time series data. We will be using pandas’ read_csv method to plot the time series data:-

# plot_time_series.py

data = pd.read_csv('plot_time_series.csv')
price_date = data['Date']
price_close = data['Close']
plt.plot_date(price_date, price_close, linestyle='solid')

plot_time_series_python_.png

Converting the dates to datetime format

One thing to note here is that the dates on x-axis are shown as strings and not the dates so DateFormatter won’t work on that. To make them date objects, we will be using pandas.to_datetime.

# plot_time_series.py

import matplotlib.pyplot as plt
from datetime import datetime, timedelta
from matplotlib import dates as mpl_dates
import pandas as pd
plt.style.use('seaborn')

data = pd.read_csv('plot_time_series.csv')
data['Date'] = pd.to_datetime(data['Date'])
data.sort_values('Date', inplace=True)
price_date = data['Date']
price_close = data['Close']
plt.plot_date(price_date, price_close, linestyle='solid')
plt.gcf().autofmt_xdate()
date_format = mpl_dates.DateFormatter('%d-%m-%Y')
plt.gca().xaxis.set_major_formatter(date_format)
plt.tight_layout()
plt.title('Bitcoin Prices')
plt.xlabel('Date')
plt.ylabel('Closing')
plt.show()

plot_time_series_python.png

So, in this tutorial we have learned to plot time series data in python from raw data as well as csv using pandas. We also learned how to change the scatter time series plot to line time series plot and much more.

Matplotlib Video Tutorial Series

We are glad to inform you that we are coming up with the Video Tutorial Series of Matplotlib on Youtube. Check it out below.

Table of Contents of Matplotlib Tutorial in Python

Matplotlib Tutorial in Python | Chapter 1 | Introduction

Matplotlib Tutorial in Python | Chapter 2 | Extracting Data from CSVs and plotting Bar Charts

Pie Charts in Python | Matplotlib Tutorial in Python | Chapter 3

Matplotlib Stack Plots/Bars | Matplotlib Tutorial in Python | Chapter 4

Filling Area on Line Plots | Matplotlib Tutorial in Python | Chapter 5

Python Histograms | Matplotlib Tutorial in Python | Chapter 6

Scatter Plotting in Python | Matplotlib Tutorial | Chapter 7

Plot Time Series in Python | Matplotlib Tutorial | Chapter 8

Python Realtime Plotting | Matplotlib Tutorial | Chapter 9

Matplotlib Subplot in Python | Matplotlib Tutorial | Chapter 10

Python Candlestick Chart | Matplotlib Tutorial | Chapter 11

In the next tutorial we will be learning to plot live data in real-time. Stay tuned.

If you have liked our tutorial, there are various ways to support us, the easiest is to share this post. You can also follow us on facebook, twitter and youtube.

In case of any query, you can leave the comment below.

If you want to support our work. You can do it using Patreon.


Related Posts

Chapter 2 - Quick setup
By Udit Vashisht

How to install Python?

It doesn’t matter which OS you are using, Python3 comes with multiple OS compatibility.

Install Python on Windows PC

Follow the steps in this post to install Python on Windows PC.

Install Python on MacOS/Linux

Follow the steps in this post ...

Read More
Scatter Plotting in Python | Matplotlib Tutorial | Chapter 7
By Udit Vashisht

Scatter Plot in Python using Pandas and Matplotlib

In this tutorial we will learn to create a Scatter Plot in Python using Matplotlib and Pandas. We will use matplotlib.pyplot()’s plt.scatter() to create the scatter plot

What is a Scatter Plot?

Scatter Plot also known as scatter plots ...

Read More
Python Realtime Plotting | Matplotlib Tutorial | Chapter 9
By Udit Vashisht

Python Realtime Plotting in Matplotlib

Python Realtime Plotting | Chapter 9

In this tutorial, we will learn to plot live data in python using matplotlib. In the beginning, we will be plotting realtime data from a local script and later on we will create a python live plot ...

Read More
Search
Tags
tech tutorials automate python beautifulsoup web scrapping webscrapping bs4 Strip Python3 programming Pythonanywhere free Online Hosting hindi til github today i learned Windows Installations Installation Learn Python in Hindi Python Tutorials Beginners macos installation guide linux SaralGyaan Saral Gyaan json in python JSON to CSV Convert json to csv python in hindi convert json csv in python remove background python mini projects background removal remove.bg tweepy Django Django tutorials Django for beginners Django Free tutorials Proxy Models User Models AbstractUser UserModel convert json to csv python json to csv python Variables Python cheats Quick tips == and is f string in python f-strings pep-498 formatting in python python f string smtplib python send email with attachment python send email automated emails python python send email gmail automated email sending passwords secrets environment variables if name == main Matplotlib tutorial Matplotlib lists pandas Scatter Plot Time Series Data Live plots Matplotlib Subplots Matplotlib Candlesticks plots Tutorial Logging unittest testing python test Object Oriented Programming Python OOP Database Database Migration Python 3.8 Walrus Operator Data Analysis Pandas Dataframe Pandas Series Dataframe index pandas index python pandas tutorial python pandas python pandas dataframe python f-strings padding how to flatten a nested json nested json to csv json to csv python pandas Pandas Tutorial insert rows pandas pandas append list line charts line plots in python Django proxy user model django custom user model django user model matplotlib marker size pytplot legends scatter plot python pandas python virtual environment virtualenv venv python python venv virtual environment in python python decorators bioinformatics fastafiles Fasta python list append append raspberry pi editor cron crontab Cowin Cowin api python dictionary Python basics dictionary python list list ios development listview navigationview swiftui ios mvvm swift environmentobject property wrapper @State @Environm popup @State ios15 alert automation instagram instaloader texteditor youtubeshorts textfield multi-line star rating reusable swift selenium selenium driver requests-html youtube youtube shorts python automation python tutorial algo trading nifty 50 nifty50 stock list nifty50 telegram telegram bot dictionary in Python how to learn python learn python