24 Python: Matplotlib

  • Matplotlib is a comprehensive library for creating

  • The package is integrated with other third party packages


24.1 Matplotlib: Overview

  • Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python

  • Matplotlib: Visualization with Python

  • Matplotlib can create high-quality plots and interactive figures

  • Many components of Matplotlib are similar to R base plot, although implementation is different

  • It is integrated with pandas and many third party packages

  • See the previous chapter for pandas implementation of Matplotlib

  • Here we present a typical implementation of Matplotlib

  • See Matplotlib tutorials for a comprehensive usage of the package

  • The link for quick tips and tricks of Matplotlib options

  • Install Matplotlib from PyPI repository: pip install matplotlib


24.2 A Typical Implementation of Matplotlib

24.2.1 Load Libraries & Read Data

Import matplotlib

import matplotlib.pyplot as plt

Import other libraries

import pandas as pd

import numpy as np

Set the working directory to the data folder

Read the iris dataset as a Python object DF

DF = pd.read_csv('iris.csv')


24.2.2 Implementation


# A figure with a single axes
fig, ax = plt.subplots()

# Create scatter plot
colors = {'setosa': 'red', 'versicolor': 'blue', 'virginica': 'green'}
Species = DF.Species.unique()
ax.scatter(x = DF.SepalLength, y = DF.PetalLength, marker = 'o', c = DF.Species.map(colors), alpha = 0.5)

# Axes labels
ax.set_xlabel('Sepal Length (cm)')
ax.set_ylabel('Petal Length (cm)');

# Legends
# ax.legend()

# Show plot
plt.show()

24.3 Components of a Matplotlib Figure

Source: https://matplotlib.org/stable/tutorials/introductory/usage.html