How to plot a time series in python ?


Introduction

A time series is a sequence of data points that are collected at successive time intervals. This type of data is commonly used to analyze trends and patterns over time. It is important to know how to visualize and analyze such data in order to gain insights and make predictions.

In this tutorial, we will learn how to plot a time series in python using the numpy library.

Plot a time series using matplotlib

Before diving into advanced time series analysis with Python, it is vital to master the fundamentals of plotting a basic time series using matplotlib. Here, we present a simple example that encompasses all the essential tools needed for plotting a time series:

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

x_values = [1.,2.,3.,4.,5.]

x_tick_positions = [1.,2.,3.,4.,5.]
x_tick_labels = ['2019-08-01','2019-08-02','2019-08-03','2019-08-04','2019-08-05']

y_values = [2,1,2,1,2]

plt.plot(x_values,y_values)

plt.xlabel('Days', fontsize=14)
plt.ylabel('Values', fontsize=14)

plt.title('How to plot a time series in python ?', fontsize=14)

plt.xticks(x_tick_positions, x_tick_labels, rotation=45, fontsize=14)
plt.yticks(fontsize=14)

plt.savefig('time_series_01.png', dpi=100, bbox_inches='tight')

plt.show()

The resulting plot should look like this:

How to plot a time series in python ?
How to plot a time series in python ?

Customizing the Time Series Plot

There are various methods for customizing the time series plot. Let's explore the essential tools that you may find useful.

Increasing the padding between axis titles and tick labels

To enhance the spacing between axis titles and tick labels, you can increase the padding.

To enhance the clarity and aesthetics of the plot, consider increasing the spacing between the axis title and tick labels. This can be achieved by using the keyword argument labelpad in the matplotlib package. The labelpad allows you to specify the amount of space between axis titles and tick labels, giving more breathing room for readers to easily make sense of your time series plot:

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

x_values = [1.,2.,3.,4.,5.]

x_tick_positions = [1.,2.,3.,4.,5.]
x_tick_labels = ['2019-08-01','2019-08-02','2019-08-03','2019-08-04','2019-08-05']

y_values = [2,1,2,1,2]

plt.plot(x_values,y_values)

plt.xlabel('Days', fontsize=14, labelpad=20)
plt.ylabel('Values', fontsize=14, labelpad=20)

plt.title('How to plot a time series in python ?', fontsize=14)

plt.xticks(x_tick_positions, x_tick_labels, rotation=45, fontsize=14)
plt.yticks(fontsize=14)

plt.savefig('time_series_02.png', dpi=100, bbox_inches='tight')

plt.show()

Output:

How to plot a time series in python ?
How to plot a time series in python ?

Increasing the padding between tick labels and the axis in python

if you want to create a plot that is easy to read and visually appealing, it's also important to know how to properly adjust the padding between the tick labels and axis.

To increase the padding between tick labels and axis in python, we can use the tick_params() method from matplotlib. This method allows us to specify various parameters for the ticks on the plot, such as size, color, and padding.

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

x_values = [1.,2.,3.,4.,5.]

x_tick_positions = [1.,2.,3.,4.,5.]
x_tick_labels = ['2019-08-01','2019-08-02','2019-08-03','2019-08-04','2019-08-05']

y_values = [2,1,2,1,2]

plt.plot(x_values,y_values)

plt.xlabel('Days', fontsize=14, labelpad=20)
plt.ylabel('Values', fontsize=14, labelpad=20)

plt.title('How to plot a time series in python ?', fontsize=14)

plt.xticks(x_tick_positions, x_tick_labels, rotation=45, fontsize=14)
plt.yticks(fontsize=14)

ax.tick_params(axis='x', which='major', pad=15)

plt.savefig('time_series_03.png', dpi=100, bbox_inches='tight')

plt.show()

Output:

How to plot a time series in python ?
How to plot a time series in python ?

Customizing Tick Label Colors in matplotlib

In the previous section, we learned how to customize tick labels and axis appearance in Matplotlib. In this section, we will explore another aspect of customization by focusing on changing the color of tick labels.

Tick labels are an integral part of any plot as they provide information about the data points being plotted. By default, Matplotlib assigns a black color to tick labels, but this can be changed as per the user's preference.

To change the color of tick labels, we use the "color" parameter in the plt.xticks() method. For example, if we want to change the color of tick labels to red, we would pass in "red" as the argument for the "color" parameter:

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

x_values = [1.,2.,3.,4.,5.]

x_tick_positions = [1.,2.,3.,4.,5.]
x_tick_labels = ['2019-08-01','2019-08-02','2019-08-03','2019-08-04','2019-08-05']

y_values = [2,1,2,1,2]

plt.plot(x_values,y_values)

plt.xlabel('Days', fontsize=14, labelpad=20)
plt.ylabel('Values', fontsize=14, labelpad=20)

plt.title('How to plot a time series in python ?', fontsize=14)

plt.xticks(x_tick_positions, x_tick_labels, rotation=45, fontsize=14, color='red')
plt.yticks(fontsize=14)

ax.tick_params(axis='x', which='major', pad=15)

plt.savefig('time_series_04.png', dpi=100, bbox_inches='tight')

plt.show()

Output:

How to plot a time series in python ?
How to plot a time series in python ?

Customizing matplotlib axis colors

With the help of ax spines set_color, you can easily change the color of your axes in just a few lines of code.

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

x_values = [1.,2.,3.,4.,5.]

x_tick_positions = [1.,2.,3.,4.,5.]
x_tick_labels = ['2019-08-01','2019-08-02','2019-08-03','2019-08-04','2019-08-05']

y_values = [2,1,2,1,2]

plt.plot(x_values,y_values)

plt.xlabel('Days', fontsize=14, labelpad=20)
plt.ylabel('Values', fontsize=14, labelpad=20)

plt.title('How to plot a time series in python ?', fontsize=14)

plt.xticks(x_tick_positions, x_tick_labels, rotation=45, fontsize=14, color='red')
plt.yticks(fontsize=14)

ax.tick_params(axis='x', which='major', pad=15)

ax.spines['bottom'].set_color('red')
ax.spines['top'].set_color('red') 
ax.spines['right'].set_color('red')
ax.spines['left'].set_color('red')

plt.savefig('time_series_05.png', dpi=100, bbox_inches='tight')

plt.show()

Output:

How to plot a time series in python ?
How to plot a time series in python ?

Advanced features

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

x_values = [1.,2.,3.,4.,5.]

x_tick_positions = [1.,2.,3.,4.,5.]
x_tick_labels = ['2019-08-01','2019-08-02','2019-08-03','2019-08-04','2019-08-05']

y_values = [2,1,2,1,2]

plt.plot(x_values,y_values)

plt.xlabel('Days', fontsize=14, labelpad=20)
plt.ylabel('Values 1', fontsize=14, labelpad=20)

plt.title('How to plot a time series in python ?', fontsize=14)

plt.xticks(x_tick_positions, x_tick_labels, rotation=45, fontsize=14, color='lightblue')
plt.yticks(fontsize=14)

#------------------------------------------------------#

ax_secondary = ax.twinx()
ax_secondary.plot(x_values,[1,1,1,1,1], color='coral' )

ax_secondary.tick_params(axis='y', colors='coral', labelsize=14) 
ax_secondary.set_ylabel('Values 2', color='coral', fontsize=14, labelpad=20)

#------------------------------------------------------#

plt.savefig('time_series_06.png', dpi=100, bbox_inches='tight')

plt.show()

Output:

How to plot a time series in python ?
How to plot a time series in python ?

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

x_values = [1.,2.,3.,4.,5.]

x_tick_positions = [1.,2.,3.,4.,5.]
x_tick_labels = ['2019-08-01','2019-08-02','2019-08-03','2019-08-04','2019-08-05']

y_values = [2,1,2,1,2]

plt.plot(x_values,y_values)

plt.xlabel('Obs 1', fontsize=14, labelpad=20)
plt.ylabel('Values 1', fontsize=14, labelpad=20)

plt.title('How to plot a time series in python ?', fontsize=14, pad=15)

plt.xticks(x_tick_positions, x_tick_labels, rotation=90, fontsize=14, color='lightblue')
plt.yticks(fontsize=14)

#------------------------------------------------------#

x2_values = [1.5, 3.2, 4.2]

x2_tick_positions = [1.5, 3.2, 4.2]
x2_tick_labels = ['2019-08-01 12H30','2019-08-02 12H30','2019-08-03 12H30']

y2_values = [1.5, 1.5, 1.5]

def identity_func(x):
    return x

ax_secondary = ax.secondary_xaxis('top', functions=(identity_func, identity_func))

plt.scatter(x2_values, y2_values, color='coral' )

ax_secondary.tick_params(axis='x', colors='coral', labelsize=14) 
ax_secondary.set_xlabel('Obs 2', color='coral', fontsize=14, labelpad=20)

ax_secondary.set_xticks(x2_tick_positions)
ax_secondary.set_xticklabels(x2_tick_labels, rotation=90, fontsize=14)

#------------------------------------------------------#

plt.savefig('time_series_07.png', dpi=100, bbox_inches='tight')

plt.show()

Output:

How to plot a time series in python ?
How to plot a time series in python ?

References

Links Site
Image

of