With matplotlib
one can easily create professional graphs and plots using numpy, scipy or pandas data.
Only brief overview here, many nice examples in: http://scipy-cookbook.readthedocs.org/items/idx_matplotlib_simple_plotting.html
matplotlib
can be used both for
When working in Jupyter one usually shows the graphs directly in the notebook:
%matplotlib inline
Or one uses separate graphics window:
%matplotlib qt
(on Linux, some extra functionality like zooming or storing)More recently the package ipympl
was introduced which provides additional interactive functionality for inline graphs in notebooks
%matplotlib widget
#%matplotlib inline
%matplotlib widget # for interactive widgets
import numpy as np
# common matplotlib shorthands
import matplotlib.pyplot as plt
x = np.linspace(0, 10, 100)
fig = plt.figure()
plt.plot(x, np.sin(x))
po=plt.plot(x, np.cos(x))
x = np.linspace(0, 10, 100)
fig = plt.figure() # get handle to matplotlib figure first
plt.plot(x, np.sin(x),'-')
plt.plot(x, np.cos(x),'--')
fig.savefig('my_figure.png') # call save method for this figure
!ls -l my_figure.png # check it got actually created
t = np.linspace(0, 5, 100)
v1 = np.cos(2*2*np.pi*t)
v2 = np.sin(2*np.pi*t)
fig = plt.figure()
plt.plot(t, v1,'-',label='Voltage-1')
plt.plot(t, v2,'--',label='Voltage-2')
plt.xlabel('time (s)') # x-axis
plt.ylabel('voltage (mV)')# y-axis
plt.title('About as simple as it gets, folks') # title header
plt.grid(True)
plt.legend();
fig = plt.figure()
plt.plot(x, np.sin(x - 0), color='blue') # specify color by name
plt.plot(x, np.sin(x - 1), color='g') # short color code (rgbcmyk)
plt.plot(x, np.sin(x - 2), color='0.75') # Grayscale between 0 and 1
plt.plot(x, np.sin(x - 3), color='#FFDD44') # Hex code (RRGGBB from 00 to FF)
plt.plot(x, np.sin(x - 4), color=(1.0,0.2,0.3)) # RGB tuple, values 0 to 1
plt.plot(x, np.sin(x - 5), color='chartreuse'); # all HTML color names supported
fig = plt.figure()
plt.plot(x, x + 0, linestyle='solid')
plt.plot(x, x + 1, linestyle='dashed')
plt.plot(x, x + 2, linestyle='dashdot')
plt.plot(x, x + 3, linestyle='dotted');
# For short, you can use the following codes:
plt.plot(x, x + 4, linestyle='-') # solid
plt.plot(x, x + 5, linestyle='--') # dashed
plt.plot(x, x + 6, linestyle='-.') # dashdot
plt.plot(x, x + 7, linestyle=':'); # dotted
fig = plt.figure()
# compact combined form ...
plt.plot(x, x + 0, '-g') # solid green
plt.plot(x, x + 1, '--c') # dashed cyan
plt.plot(x, x + 2, '-.k') # dashdot black
plt.plot(x, x + 3, ':r'); # dotted red
fig = plt.figure()
plt.plot(x, np.sin(x))
plt.axis([-1, 11, -1.5, 1.5]); # just a list with xmin, xmax, ymin, ymax
For simple cases one can just use plt.plot
with key o
:
x = np.linspace(0, 10, 30)
fig = plt.figure() # get handle to matplotlib figure first
plt.plot(x, np.sin(x),'o')
plt.plot(x, np.cos(x),'+');
# marker demo
# plot 5 random x,y pairs for each std marker type
#
fig = plt.figure()
for marker in ['o', '.', 'v', '^', '<', '>', 's', 'd']:
plt.plot(np.random.random(5), np.random.random(5), marker,
label="marker='{0}'".format(marker))
plt.legend(numpoints=1)
plt.xlim(0, 1.8);
$\rightarrow$ visualize 3rd and 4th dimension
x = np.random.randn(100) # gauss rnd
y = np.random.randn(100)
colors = np.random.random(100) # uniform rand
sizes = 1000 * np.random.random(100)
fig = plt.figure()
plt.scatter(x, y, c=colors, s=sizes, alpha=0.3,
cmap='viridis')
plt.colorbar(); # show color scale
Scientific data, in particular in physics, often has errors associated to the y-coordinate (sometimes also to x)
x = np.linspace(0, 10, 50)
y = np.sin(x) + 0.5*np.random.randn(50)
fig = plt.figure()
#plt.errorbar(x, y, 0.7, fmt='ob'); # fixed error in y, can also be array
plt.errorbar(x, y, 0.5*y, fmt='ob');
Fundamental plot type to visualize data distributions, mostly in 1D but also 2D or even 3D
# simple 1d histogram
#
mu, sigma = 100, 15
x = np.random.normal(mu,sigma,10000)
fig = plt.figure()
# the histogram of the data
plt.hist(x,bins=50, range=(80,120)) # args: array to fill, num-bins
plt.title(r'$\mathrm{Histogram\ of\ IQ:}\ \mu=100,\ \sigma=15$'); # Latex syntax for math
plt.hist?
Many options how to fill and display histograms
# demonstrate overlaying several histos
x1 = np.random.normal(0, 0.8, 1000)
x2 = np.random.normal(-2, 1, 1000)
x3 = np.random.normal(3, 2, 1000)
# Options:
# density=True -- normalized to 1
# alpha=0.3 -- transparency of fill
# histtype='stepfilled' -- only filled bar, no line in between
kwargs = dict(histtype='stepfilled', alpha=0.3, density=True, bins=40)
fig = plt.figure()
plt.hist(x1, **kwargs)
plt.hist(x2, **kwargs)
plt.hist(x3, **kwargs);
2 variables can of course be plotted as x-y point plot:
mean =[0, 0]
cov = [[1, 1], [1, 2]]
x, y = np.random.multivariate_normal(mean, cov, 10000).T # generate correlated random points
fig = plt.figure()
plt.plot(x,y,'.');
But often more instructive to use 2D histo
fig = plt.figure()
plt.hist2d(x, y, bins=30, cmap='Blues')
cb = plt.colorbar()
cb.set_label('counts in bin')
Using interact
from ipywidgets
package one can create graphs with interactive control
from ipywidgets import interact
import numpy as np
import matplotlib.pyplot as plt
#%matplotlib inline
%matplotlib widget
x = np.linspace(0, 2 * np.pi,100)
fig = plt.figure(1,figsize=(6,4))
line, = plt.plot(x, np.sin(x))
def update(w = 1.0):
line.set_ydata(np.sin(w * x))
fig.canvas.draw()
interact(update, w=(0.5,10,0.1));
Of course there are many more features in matplotlib
, such as
We will see some of that in the following chapters.