SaralGyaan, Saral Gyaan, Saral Gyan is website which provides free tutorials of Python for absolute beginners in English and Hindi, Learn Python in Hindi, Learn Python for absolute beginners, Learn Python, bootstrap, django, git

Hari S
Author: Hari S


Plot Time Series in Python | Matplotlib Tutorial | Chapter 8

  • Sept. 6, 2019, 11:27 a.m.
  • 4 minutes read
  • 29 Views
Plot Time Series in Python | Matplotlib Tutorial | Chapter 8

Plot Time Series in Python using Matplotlib

Plot Time Series in Python | Chapter 8

In this tutorial we will learn to plot time series data in Python using Matplotlib. We will also be using pandas dataframe to plot time series data in python from a CSV file using pandas.read_csv().

Plotting simple Time Series Data in Python using Matplotlib

First of all, we will simply plots dates in Matplotlib. We will be using python’s in-built module called datetime(datetime, timedelta). So, let us create a python file called ‘plot_time_series.py’ and make necessary imports.

We will be using seaborn style to plot the time series data. Finally, we will be passing arguments to plt.plot_date() method and call plt.show() to plot and show the time series data in Matplotlib.

# 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

If we want to change this scatter plot time series data to a line, we can pass linestyle argument to pplt.plot_date(). We can change the also change the markers.

# plot_time_series.py

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

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 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

Plot time series data in Python from 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 plotting that time series data 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

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.

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

How to host and schedule your python script on PythonAnywhere?
By Hari S | 8 months ago

In our last post here, we learned how to create a python script which will automatically delete your messages from gmail account based on a query.

The complete ready-to-use code can be found here.

Follow the steps in the above tutorial to download the ‘credentials.json’ file and ...

Read More
Python Tutorial for Beginners
By Hari S | 7 months, 4 weeks ago

Python Tutorial for Beginners

Best Python Tutorial, Free Python Tutorial, Python Tutorial Pdf. Does these terms sound familiar, You must have searched about python tutorials in the google search bar. Your search for the Best Python Tutorial is over.

We are excited to bring Python tutorial for a complete beginner ...

Read More
Chapter 3 - Executing a Python Script
By Hari S | 7 months, 2 weeks ago

In our previous chapter, we have strongly recommended you to ditch IDLE and use some code-editor and terminal(MacOS/Linux) or Powershell(Windows) to write and execute your python script. In this chapter we will tell you how to do that.

First and foremost for the purpose of this tutorial, create a new ...

Read More
Search