# Python - Plot time series in a DataFrame

This post is written for documentation purpose. It covers the following topics of matplotlib:

• how to plot time series?
• how to add label ticks?
• how to rotate labels?
• how to set the font size of labels?
• how to save plot to an image.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import pandas as pd; pd.set_option("expand_frame_repr", False)
import matplotlib.pyplot as plt
import numpy as np

def plotDataFrame(df, columns, t_col,
title="UNKNOWN TITLE",
labelDivider=10,
outImageFile=None,
x_label="timestamp", y_label=None,
x_labelRotationInDegree=90,
labelFontSize=6,
legendLocation="upper right",
alpha=1.0):
"""
Plots the DataFrame.

:param df: The data frame to plot.
:param columns: The names of the time series that we want to plot.
:param t_col: The column name that represents the time.
:param title: The title of the graph.
:param labelDivider: 1 / labelDivider of t_col columns are added to the x label.
:param outImageFile: The output image file name. If it's set to None, this function will plot the figure.
:param x_label: X label of the plot.
:param y_label: Y label of the plot.
:param x_labelRotationInDegree:
:param labelFontSize: Font size of the label.
:param legendLocation: Location of the legend.
:param alpha: The alpha channel of the image.
"""
fix, ax = plt.subplots(1)

for column in columns:
plt.plot(df[column].values, label=column, alpha = alpha)

plt.legend(loc=legendLocation)
plt.title(title)

xTickLabels = df[t_col].values
xTicks = np.arange(xTickLabels.size)
tickPicked = [x for x in xTicks if x % labelDivider == 0]

ax.set_xticks(xTicks[tickPicked])
ax.set_xticklabels(xTickLabels[tickPicked])

ax.set_xlabel(x_label)

if y_label is not None:
ax.set_ylabel(y_label)

for tick in ax.get_xticklabels():
tick.set_rotation(x_labelRotationInDegree)
tick.set_fontsize(labelFontSize)

if outImageFile is None:
plt.show()
else:
plt.savefig(outImageFile, bbox_inches = 'tight')


Here is an example of the usage of this function:

1
2
plotDataFrame(df, ["Open", "High", "Low", "Close"],
t_col="Date", labelDivider=20, title="TSLA", x_label="date", legendLocation="upper left")


And here is the graph generated:

----- END -----

Welcome to join reddit self-learning community.

Want some fun stuff?