Applied Machine Learning for Engineers
FS 2020 - B. Vennemann
Data Visualization with Matplotlib
What is Matplotlib
A Matlab-style plotting library for Python
Can produce publication-ready figures
Can be run in Python scripts, Python shells, Ipython shells, Jupyter notebooks, ...
Installation: conda install -c conda-forge matplotlib
Import the pyplot submodule with alias plt
In [1]:
import matplotlib.pyplot as plt
Use Jupyter Notebook line magic for plotting inside the notebook
In [2]:
%matplotlib inline
Simple line plots
In [3]:
import numpy as np
In [4]:
x = np.linspace(0, 5, 50)
In [5]:
plt.plot(x, x, label='linear curve')
plt.plot(x, x**2, label='quadratic curve')
plt.legend()
plt.xlabel('x')
plt.ylabel('y')
plt.title('my interesting plot')
plt.show()
Example using subplots
In [6]:
plt.figure(figsize=(10, 4))
plt.subplot(1, 2, 1)
plt.plot(x, x, label='linear curve')
plt.legend()
plt.title('first subplot')
plt.subplot(1, 2, 2)
plt.plot(x, x**2, label='quadratic curve')
plt.legend()
plt.title('second subplot')
plt.show()
Example using line styles
In [7]:
plt.plot(x, x, 'g--', x, x**2, 'r.-', x, x**3, 'bo', linewidth=3)
plt.show()
Scatter plots
In [8]:
x = np.random.random(20)
y = np.random.random(20)
plt.scatter(x, y)
plt.show()
Example using more advanced scatter plot features
In [9]:
plt.scatter(x, y, s=500*y, c=x, cmap='cool') # x encoded as color and y encoded as size
plt.show()
Bar plots
In [10]:
category_names = ['Group A', 'Group B', 'Group C']
values = [5, 9, 3]
plt.bar(category_names, values)
plt.show()
Annotations, text and histograms
In [11]:
x = np.random.randn(10000)
plt.figure(figsize=(8, 5))
plt.hist(x, bins=50)
plt.text(-3, 500, 'some text')
plt.annotate('normal distribution', xy=(1, 450), xytext=(1.8, 550),
arrowprops=dict(facecolor='black', width=2))
plt.show()
Further reading
More info at https://matplotlib.org/contents.html (https://matplotlib.org/contents.html)