This post is written for documentation purpose. It covers the following topics of matplotlib:
- how to plot time series?
- how to add legend?
- how to add title?
- how to add labels?
- how to add label ticks?
- how to rotate labels?
- how to set the font size of labels?
- how to save plot to an image.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
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:
12
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 -----
©2019 - 2023 all rights reserved