Introduction to Matplotlib on Python

Fundi Willy 楚大洋
3 min readJul 27, 2017

--

Matplotlib is a Python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms. Matplotlib can be used in Python scripts and the jupyter notebook, web application servers, and four graphical user interface toolkits.

matplotlib logo

matplotlib is the go to python tool for representing data like a pro. I started learning it yesterday and am impressed so far. I came across matplotlib when working on Step1 of Project 2 of Udacity Self Driving Car Nanodegree Programme. The instructions were simple, Visualize the German Traffic Signs Dataset using the pickled file(s). Its open ended, suggestions include: plotting traffic sign images, plotting the count of each sign, etc. The Matplotlib examples and gallery pages are a great resource for doing visualizations in Python. NOTE: It’s recommended you start with something simple first. If you wish to do more, come back to it after you’ve completed the rest of the sections.

If you are familiar with Matlab by Mathworks, then matplotlib will be a piece of cake.

Heading over to the matplotlib website, I started some small examples like below..

One thing to not we import matlplotlib.pyplot as np. matplotlib.pyplot is a collection of command style functions that make matplotlib work like MATLAB. Each pyplot function makes some change to a figure: e.g., creates a figure, creates a plotting area in a figure, plots some lines in a plotting area, decorates the plot with labels. Most of the code is easy to understand as self explanatory.

#WilfredGithuka
#Githuka.com
#AnnotatingText

import numpy as np
import matplotlib.pyplot as plt

ax = plt.subplot(111)

t = np.arange(0.0, 5.0, 0.01)
s = np.cos(2*np.pi*t)
line, = plt.plot(t, s, lw=2)

plt.annotate(‘max amplitute of voltage’, xy=(2, 1), xytext=(3, 1.5),
arrowprops=dict(facecolor=’black’, shrink=0.05),
)
plt.yscale(‘log’)
plt.title(‘Single Phase Voltage’)
plt.ylim(-2,2)
plt.ylabel(‘Voltage’)
plt.xlabel(‘Current’)
plt.show()

Basic plotting with matplot.pyplot

Histograms

#WilfredGithuka
#Githuka.com
#Matplotlib-Histogram

import numpy as np
import matplotlib.pyplot as plt

#Fixing random state for reproducibility
np.random.seed(19680801)

mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)

#Histogram
n, bins, patches = plt.hist(x, 50, normed=1, facecolor=’g’, alpha=0.75)

plt.xlabel(‘Smarts’)
plt.ylabel(‘Probability’)
plt.title(‘Histogram of IQ’)
plt.text(60, .025, r’$\mu=100,\ \sigma=15$’)
plt.axis([40, 160, 0, 0.03])
plt.grid(True)
plt.show()

Plotting Histograms

Annotating Text

The uses of the basic text() command above place text at an arbitrary position on the Axes. A common use for text is to annotate some feature of the plot, and the annotate() method provides helper functionality to make annotations easy. In an annotation, there are two points to consider: the location being annotated represented by the argument xy and the location of the text xytext. Both of these arguments are (x,y) tuples.

In the following code, I was experimenting some styles with Logarithmic scales (math fan) The line plt.yscale(‘log’) can be omitted to have different results.

#WilfredGithuka
#Githuka.com
#AnnotatingText

import numpy as np
import matplotlib.pyplot as plt

ax = plt.subplot(111)

t = np.arange(0.0, 5.0, 0.01)
s = np.cos(2*np.pi*t)
line, = plt.plot(t, s, lw=2)

plt.annotate(‘max amplitute of voltage’, xy=(2, 1), xytext=(3, 1.5),
arrowprops=dict(facecolor=’black’, shrink=0.05),
)
plt.yscale(‘log’)
plt.title(‘Single Phase Voltage’)
plt.ylim(-2,2)
plt.ylabel(‘Voltage’)
plt.xlabel(‘Current’)
plt.show()

A weired output with the plt.yscale(‘log’)
a more clear outut without plt.yscale(‘log’).Note the way you can annotate text all in code :-)

Thats all for now, back to Visualisation.

Circuit Open [ — \ — ]

--

--

Fundi Willy 楚大洋

Electrical, Automation & Self-Driving Vehicles | Udacity Self Driving Car ND | My Garage >> www.githuka.com