# Matplotlib time series plot

In this Python Matplotlib tutorial, we’ll discuss the Matplotlib time series plot. Here we’ll cover different examples related to the time series plot using matplotlib. And we’ll also cover the following topics:

• Matplotlib time series
• Matplotlib time series plot pandas
• Matplotlib time series scatter plot
• Matplotlib multiple time series plot
• Matplotlib time series bar plot
• Matplotlib plot time series x axis
• Python time series plot seaborn
• Matplotlib boxplot time series
• Python time series interactive plot
• Matplotlib time series multiple bar plot
• Matplotlib plot time series with gaps

## Matplotlib time series

Here first, we will understand what is time series plot and discuss why do we need it in matplotlib.

### What is Time Series Plot:

Time Series data is a collection of data points that were collected over a period of time and are time-indexed. These observations are made at evenly spaced intervals throughout time. Data visualization plays an important role in plotting time series plots.

### Where we need Time Series Plot:

The ECG signal, EEG signal, stock market data, weather data, and so on are all time-indexed and recorded over a period of time. The field of research for analyzing this data and forecasting future observations is much broader.

Also, check: Matplotlib update plot in loop

## Matplotlib time series plot pandas

Here we learn to plot a time series plot that will be created in pandas. So firstly, we have to create a sample dataset in pandas.

The following is the syntax to create DataFrame in Pandas:

``pandas.DataFrame(data, index, columns, dtype, copy)``

Let’s see the source code to create DataFrame:

``````# Import Library

import pandas as pd

# Defne Data

timeseries_data = {
'Date': ['2021-12-26', '2021-12-29',
'2021-12-27', '2021-12-30',
'2021-12-28', '2021-12-31' ],

'Washington': [42, 41, 41, 42, 42, 40],

'Canada' : [30, 30, 31, 30, 30, 30],

'California' : [51, 50, 50, 50, 50, 50]
}

# Create dataframe

dataframe = pd.DataFrame(timeseries_data,columns=['Date', 'Washington', 'Canada', 'California'])

# Changing the datatype

dataframe["Date"] = dataframe["Date"].astype("datetime64")

# Setting the Date as index

dataframe = dataframe.set_index("Date")
dataframe``````

Output:

Source Code for plotting the data:

``````# Import Library

import matplotlib.pyplot as plt

# Plot

# Labelling

plt.xlabel("Date")
plt.ylabel("Temp in Faherenheit")
plt.title("Pandas Time Series Plot")

# Display

plt.show()``````
• Firstly, import matplotlib.pyplot library.
• Next, plot the graph for the Canada column.
• To add labels at axes, we use xlabel() and ylabel() function.
• To add the title, we use the title() function.

Output:

Also, read: Matplotlib fill_between – Complete Guide

## Matplotlib time series scatter plot

Now here we learn to plot time-series graphs using scatter charts in Matplotlib.

Example:

In this example, we take above create DataFrame as a data.

``````# Import Library

import matplotlib.pyplot as plt

# Plot scatter

plt.scatter(dataframe.index, dataframe["Washington"])

# Labelling

plt.xlabel("Date")
plt.ylabel("Temp in Faherenheit")

# Auto space

plt.tight_layout()

# Display

plt.show()``````

Here we draw a scatter plot between and Date and Temp of Washington.

## Matplotlib multiple time series plot

Here we’ll learn to plot multiple time series in one plot using matplotlib.

Example:

``````# Import Libraries

import matplotlib.pyplot as plt
import datetime
import numpy as np
import pandas as pd

# Create figure

fig = plt.figure(figsize=(12, 8))

# Define Data

df1 = pd.DataFrame({'date': np.array([datetime.datetime(2021,
12, i+1) for i in range(20)]),
'blogs_read': [4, 6, 5, 8, 15, 13, 18, 6, 5,
3, 15, 14, 19, 21, 15, 19, 25, 24, 16, 26]})

df2 = pd.DataFrame({'date': np.array([datetime.datetime(2021,
12, i+1)
for i in range(20)]),
'blogs_unread': [1, 1, 2, 3, 3, 3, 4, 3, 2,
3, 4, 7, 5, 3, 2, 4, 3, 6, 1, 2]})

# Plot time series

linewidth=3)

plt.title('Blogs by Date')
plt.xlabel('Date')
plt.ylabel('Blogs')

plt.legend()

# Auto space

plt.tight_layout()

# Display plot

plt.show() ``````
• Firstly, import the necessary libraries such as matplotlib.pyplot, datetime, numpy and pandas.
• Next, to increase the size of the figure, use figsize() function.
• To define data coordinates, we create pandas DataFrame.
• To plot the time series, we use plot() function.
• To add the title to the plot, use title() function.
• To add labels at axes, we use xlabel() and ylabel() function.
• To add legend, use legend() function.
• To display the plot, use show() function.

## Matplotlib time series bar plot

Here we’ll learn to plot time series using bar plot in Matplotlib.

Example:

``````# Import Library

import pandas as pd
import matplotlib.pyplot as plt

# Convert data frame

df=pd.DataFrame(data)

# Initilaize list

X = list(df.iloc[:,0])
Y = list(df.iloc[:,1])

# Set figure

plt.figure(figsize=(15, 12))

# Bar Plot

plt.bar(X, Y)

# Setting Ticks

plt.tick_params(axis='x',labelsize=15,rotation=90)
plt.tight_layout()

# Display

plt.show()
``````
• Firstly, we import necessary libraries such as matplotlib.pyplot, and pandas.
• Next, read the CSV file.
• After this, create DataFrame from a CSV file.
• Initialize the list for X and Y.
• To plot a bar chart, we use the bar() function.
• To change tick settings, we use tick_params() function.
• To set space, we use tight_layout() function.

## Matplotlib plot time series x axis

Here we’ll learn to set the x-axis of the time series data plot in Matplotlib.

Let’s see an example:

``````# Import Library

import matplotlib.pyplot as plt
from datetime import datetime, timedelta

# Define data

dates = [
datetime(2021, 9, 21),
datetime(2021, 9, 22),
datetime(2021, 9, 23),
datetime(2021, 9, 24),
datetime(2021, 9, 25),
datetime(2021, 9, 26),
datetime(2021, 9, 27),
]

y = [0, 1.8, 2, 3.5, 4, 5.6, 6]

# Plot

plt.plot_date(dates, y)

# Setting axes

plt.tight_layout()
plt.tick_params(axis='x', rotation=90)

# Display

plt.show()``````
• Import libraries matplotlib.pyplot and datetime.
• Define data axes x and y.
• To plot dates, we use plot_date() function.
• To set the setting of ticks, we use the tick_params() function.

## Python time series plot seaborn

Here we’ll learn how to create a time series plot with seaborn.

Seaborn is an excellent Python visualization tool for plotting statistical visuals. It includes attractive default styles and color palettes that make statistical charts more appealing. It’s based on the most recent version of the matplotlib package and is tightly integrated with pandas’ data structures.

Let’s see an example:

``````# Import Library

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

# Convert to dataframe

df=pd.DataFrame(data)

# Initilaize list

X = list(df.iloc[:,0])
Y = list(df.iloc[:,1])

# Set figure

plt.figure(figsize=(12,10))

# Seaborn

sns.lineplot(x=X, y=Y)

# Setting Ticks

plt.tick_params(axis='x',labelsize=15,rotation=90)
plt.tight_layout()

# Display

plt.show()
``````
• Firstly import matplotlib.pyplot, pandas and seaborn libraries.
• To convert the data into DataFrame, use DataFrame() function of pandas.
• To initialize the list, we use iloc() function of pandas.
• To set the figure size, use figsize() method of figure.
• To create a time series plot with seaborn library, we use lineplot() method.
• To change the setting of ticks, we use tick_params() function.
• To set the adjustment of the plot, use tight_layout() function.
• To display the plot, use show() function.

## Matplotlib boxplot time series

Here we’ll learn to plot a time-series graph using the seaborn boxplot using Matplotlib.

Example:

``````# Import libraries

import numpy as np
import pandas as pd
import seaborn
import matplotlib.pyplot as plt

# Define Data

data = pd.DataFrame(np.random.randn(100),
index=pd.date_range(start="2021-12-01",
periods=100, freq="H"))
data.groupby(lambda x: x.strftime("%Y-%m-
%d")).boxplot(subplots=False, figsize=(12,9))

# Display

plt.show()``````
• Import numpy, pandas, seaborn and matplotlib.pyplot libraries.
• Create panda data frame using DataFrame() function.
• To define the data for plotting, use random.randn() function and set index as date.
• To plot group by dates, use groupby() function.
• To create box plot graph, use boxplot() function.

## Python time series interactive plot

Plotly is a Python open-source data visualization module that supports a variety of graphs such as line charts, scatter plots, bar charts, histograms, and area plots. Plotly is a plotting tool that uses javascript to create interactive graphs.

To install Plotly use the below mention command:

``pip install plotly``

Let’s see an example:

``````# Import Library

import pandas as pd
import plotly.express as px
import matplotlib.pyplot as plt

# Convert data frame

df=pd.DataFrame(data)

# Initilaize list

X = list(df.iloc[:,0])
Y = list(df.iloc[:,1])

# Set figure

plt.figure(figsize=(12,10))

# Plotly graph

plot = px.line(x=X, y=Y)

# Setting Ticks

plt.tick_params(axis='x',labelsize=15,rotation=90)
plt.tight_layout()

# Display

plot.show()
``````
• Import necessary libraries such as pandas, plotly.express, and matplotlib.pyplot.
• Convert CSV file to data frame, using DataFrame() function.
• To initialize the list, we use iloc() function.
• To plot a interactive time series line graph, use line() function of plotly.express module.

## Matplotlib time series multiple bar plot

In this section, we’ll learn to plot time series plots using multiple bar charts. Here we plot the chart which shows the number of births in specific periodic.

Let’s see an example:

``````# Import Libraries

import pandas as pd
import matplotlib.pyplot as plt

# Creating dataframe

df = pd.DataFrame({
'Dates':['2021-06-10', '2021-06-11',
'2021-06-12', '2021-06-13',
'2021-06-14', '2021-06-15'],
'Female': [200, 350, 150, 600, 500, 350],
'Male': [450, 400, 800, 250, 500, 900]
})

# Plotting graph

df.plot(x="Dates", y=["Female", "Male"], kind="bar")

# Show

plt.show()``````

Explanation:

• Import matplotlib library for data visualization.
• Next, import pandas library to create data frame.
• Then create data frame in pandas using DataFrame() function.
• To create a multiple bar chart, we use plot() method and define its kind to bar.
• To visualize the plot, we use show() function.

## Matplotlib plot time series with gaps

We’ll learn how to plot time series with gaps in this section using matplotlib. To begin, let’s look at an illustration of what gap means:

Let’s say we have a dataset in CSV format, having some of the missing values. These blank values, or blank cells, are then substituted by NaN values. As a result, when we visualize this sort of dataset, we obtain a chart with breaks rather than continuous lines.

To understand the concept more clearly, let’s see different examples:

• Firstly, we have imported necessary libraries such as pandas and matplotlib.pyplot.
• After this, read the csv file using read_csv() function of pandas.
• To view the dataset, print it.

Source Code:

``````# Import Libraries

import pandas as pd
import matplotlib.pyplot as plt

# Print

data``````
• Next, we convert the CSV file to the panda’s data frame, using the DataFrame() function.
• If you, want to view the data frame print it.

Source Code:

``````# Convert data frame

df=pd.DataFrame(data)

# Print

df``````
• Initialize the list to select the rows and columns by position from pandas Dataframe using iloc() function.

Source Code:

``````# Initilaize list

dates = list(df.iloc[:,0])
city_1 = list(df.iloc[:,1])
city_2 = list(df.iloc[:,2])
city_3 = list(df.iloc[:,3])
city_4 = list(df.iloc[:,4])``````
• Now, set the figure size by using figsize() function.
• To set the rotation and label size of x-axis, use tick_params() function.
• To set the labels at the x-axis, use xlabel() function.
• To set the labels at the y-axis, use ylabel() function.

Source Code:

``````# Set Figure Size

plt.figure(figsize=(8,6))

# Setting Ticks

plt.tick_params(axis='x',labelsize=10,rotation=90)

# Labels

plt.xlabel("Dates")
plt.ylabel("Temp")``````
• To plot a line chart without gaps, use the plot() function and pass the data coordinates without missing values to it.
• To set a marker, pass marker as a parameter.
• To visualize the graph, use the show() function.

Example #1 (Without Gaps)

``````# Plot

plt.plot(dates, city_4, marker='o')

# Display

plt.show()``````

Example #2 (With Gaps)

``````# Set figure

plt.figure(figsize=(8,6))

# Plot

plt.plot(dates,city_1, marker='o')

# Labels

plt.xlabel("Dates")
plt.ylabel("Temp")

# Setting Ticks

plt.tick_params(axis='x',labelsize=10,rotation=90)

# Display

plt.show()``````

Example #3 (With Gaps)

Here we plot a graph between Dates and Los Angeles city.

``````# Set figure

plt.figure(figsize=(8,6))

# Plot

plt.plot(dates,city_2, marker='o')

# Labels

plt.xlabel("Dates")
plt.ylabel("Temp")

# Setting Ticks

plt.tick_params(axis='x',labelsize=10,rotation=90)

# Display

plt.show()``````

Example #4 ( With Gaps)

Here we plot a graph between Dates and Philadelphia city.

``````# Set figure

plt.figure(figsize=(8,6))

# Plot

plt.plot(dates,city_3, marker='o')

# Labels

plt.xlabel("Dates")
plt.ylabel("Temp")

# Setting Ticks

plt.tick_params(axis='x',labelsize=10,rotation=90)

# Display

plt.show()``````

Example #5 (With or Without Gap In One Plot)

``````# Set figure

plt.figure(figsize=(8,6))

# Plot

plt.plot(dates,city_1, marker='o')
plt.plot(dates,city_4, marker='o')

# Labels

plt.xlabel("Dates")
plt.ylabel("Temp")

# Setting Ticks

plt.tick_params(axis='x',labelsize=10,rotation=90)

# Display

plt.show()``````

You may also like to read the following Matplotlib tutorials.

In this Python tutorial, we have discussed the “Matplotlib time series plot” and we have also covered some examples related to it. These are the following topics that we have discussed in this tutorial.

• Matplotlib time series
• Matplotlib time series plot pandas
• Matplotlib time series scatter plot
• Matplotlib multiple time series plot
• Matplotlib time series bar plot
• Matplotlib plot time series x axis
• Python time series plot seaborn
• Matplotlib boxplot time series
• Python time series interactive plot
• Matplotlib time series multiple bar plot
• Matplotlib plot time series with gaps