Matplotlib Plotting#


see also:

# use matplotlib for plotting
import matplotlib.pylab as plt

import numpy as np

Simple Lines#

# create some test data
x = np.linspace(0, 10, 120)
y = x**2.0
plt.figure(1)

plt.plot( x, y )

plt.show()
../_images/c436db65c287a16f6540cc2b3b5e553c88dc69c41cd3a5b48d9dd9f6e22ef0f0.png

Line Styles & Viewing Modes#

plt.figure(1)

# as blue lines
#plt.plot(x, y, 
#         color='tab:blue',
#         linestyle='-')

# ... or shorter
plt.plot(x, y, 'b--')

# as red dots
plt.plot(x, y, 'r.')

plt.show()
../_images/2174046216ed895c19af56aacc662209164377c2adcec1f856832db2e969b6b4.png

Error Bars#

# load data including errors
x, y, errors = np.loadtxt('./data/03_xyerr.dat').transpose()

plt.figure(1)

plt.errorbar(x, y, errors, fmt='ro') 
# Note: Here we need to use "fmt = ..."

plt.plot(x, y, 'b-')

plt.show()
---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
Cell In[5], line 2
      1 # load data including errors
----> 2 x, y, errors = np.loadtxt('./data/03_xyerr.dat').transpose()
      4 plt.figure(1)
      6 plt.errorbar(x, y, errors, fmt='ro') 

File /usr/local/lib/python3.14/site-packages/numpy/lib/_npyio_impl.py:1397, in loadtxt(fname, dtype, comments, delimiter, converters, skiprows, usecols, unpack, ndmin, encoding, max_rows, quotechar, like)
   1394 if isinstance(delimiter, bytes):
   1395     delimiter = delimiter.decode('latin1')
-> 1397 arr = _read(fname, dtype=dtype, comment=comment, delimiter=delimiter,
   1398             converters=converters, skiplines=skiprows, usecols=usecols,
   1399             unpack=unpack, ndmin=ndmin, encoding=encoding,
   1400             max_rows=max_rows, quote=quotechar)
   1402 return arr

File /usr/local/lib/python3.14/site-packages/numpy/lib/_npyio_impl.py:1024, in _read(fname, delimiter, comment, quote, imaginary_unit, usecols, skiplines, max_rows, converters, ndmin, unpack, dtype, encoding)
   1022     fname = os.fspath(fname)
   1023 if isinstance(fname, str):
-> 1024     fh = np.lib._datasource.open(fname, 'rt', encoding=encoding)
   1025     if encoding is None:
   1026         encoding = getattr(fh, 'encoding', 'latin1')

File /usr/local/lib/python3.14/site-packages/numpy/lib/_datasource.py:192, in open(path, mode, destpath, encoding, newline)
    155 """
    156 Open `path` with `mode` and return the file object.
    157 
   (...)    188 
    189 """
    191 ds = DataSource(destpath)
--> 192 return ds.open(path, mode, encoding=encoding, newline=newline)

File /usr/local/lib/python3.14/site-packages/numpy/lib/_datasource.py:529, in DataSource.open(self, path, mode, encoding, newline)
    526     return _file_openers[ext](found, mode=mode,
    527                               encoding=encoding, newline=newline)
    528 else:
--> 529     raise FileNotFoundError(f"{path} not found.")

FileNotFoundError: ./data/03_xyerr.dat not found.

Legends & Labels#

# generate some data
x  = np.linspace(0, 5, 100)
y2 = x**2.0
y3 = x**3.0

# plot data
plt.figure(1)

#plt.plot(x, y2, color='b', label="y = x**2")
#plt.plot(x, y3, color='k', label="y = x**3")

plt.plot(x, y2, color='b', label="$y = x^2$")
plt.plot(x, y3, color='k', label="$y = x^3$")

# add legend
plt.legend(loc=2, fontsize=18)

# and x/y labels
plt.xlabel('x lab (units)')
plt.ylabel('y lab')

# don't forget about the title
plt.title('title', fontsize=20)

plt.show()
../_images/619fd57dea0de81db294136bd80e6a7008b00e76e2e69ffc9cb45014a8b9d577.png

Histograms#

# load some data
myCol1, myCol2 = np.genfromtxt('./data/01_xy.dat').transpose()

plt.figure(1)

# let's get some idea of our data by plotting a simple histogram
plt.hist(myCol1, 
         label='col 1', 
         alpha=0.5)

plt.hist(myCol2, 
         label='col 2', 
         alpha=0.5)

plt.legend()

plt.show()
../_images/fda218d87fe06f23a5d99d58b89455ff195a604c99caad0bd7f64d84888fd995.png

Example: Velocity of light as measured by Michelson#

Michelson:

  • first American to win a Nobel prize (1907)

  • disprove the existence of aether

  • measurement of speed of light:

Random

https://www.saburchill.com/physics/chapters3/0007.html

  • the time (\(t\)) taken for the light to cover the distance \(s\): $\( t = \frac{1}{8n} \)$

  • speed of light \(c\): $\( c = \frac{s}{t} = 8 n s \)$

# load data
dataMichelson = np.genfromtxt('./data/02_michelson.dat', 
                              skip_header=1)
# plot data
plt.figure(1)

plt.hist(dataMichelson, bins=15)

plt.xlabel('$v - 299.000$ (km/s)')
plt.ylabel('N')

plt.show()
# plot data
plt.figure(1)

# get some statistical data
median  = np.median(dataMichelson)
average = np.average(dataMichelson)

plt.hist(dataMichelson, bins=15, label='Michelson ')
plt.plot([792.458, 792.458], [0., 18.], label='SI')

plt.plot([median, median], [0., 18.], label='median')
plt.plot([average, average], [0., 18.], label='average')

plt.xlabel('$v - 299.000$ (km/s)')
plt.ylabel('N')

plt.legend()

plt.show()

print(average, median)

Subplots#

# create some data first
x1 = np.linspace(0.0, 5.0, 100)
x2 = np.linspace(0.0, 2.0, 100)

y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
y2 = np.cos(2 * np.pi * x2)

Simple version via plt.subplot():#

plt.figure(1)

# use subplot #1 out of a 1x2 grid
plt.subplot(2, 2, 1)

plt.plot(x1, y1)

# use subplot #2 out of a 1x2 grid
plt.subplot(2, 2, 4)

plt.plot(x2, y2)

plt.show()
../_images/45db9ebc8641b896fae8279108be423f260eee454fe0919a32b29807cce1831d.png

More sophisticated version using plt.GridSpec():#

plt.figure(1)

# create a 2x1 axis grid
grid = plt.GridSpec(nrows=2, ncols=1)

# use first axis
plt.subplot( grid[0] )
plt.plot(x1, y1)

# uses second axis
plt.subplot( grid[1] )
plt.plot(x2, y2)

plt.show()
../_images/60aa534dc708bafaf2cf25707e007192c4116a3e62098776d74b23292cef31d5.png
plt.figure(1)

# create a 2x3 axis grid
grid = plt.GridSpec(nrows=2, ncols=3)

# use complete first grid row
plt.subplot( grid[0, 0:3] )
plt.plot(x1, y1)

# use first position in second row
plt.subplot(grid[1, 0])
plt.plot(x2, y2)

# use second position in second row
plt.subplot(grid[1, 1])
plt.plot(x2, -y2)

# use third position in second row
plt.subplot(grid[1, 2])
plt.plot(x2, y2**2.0)

plt.show()
../_images/94e8c1ae7155400bef277ed27d10e734624dff8a58f1db886d23cc1b3de746c1.png

3D Plots / Colormaps#

self-defined z(x,y) data:#

import matplotlib.pylab as plt

# define x and y ranges
x = np.linspace(0, 2, 100)
y = np.linspace(0, 3, 120)

# create a x/y meshgrid
xGrid, yGrid = np.meshgrid(x, y)

# calculate some z(x,y) data from the meshgrid
z = xGrid**2 + yGrid**2

# plot it as a colormap
plt.figure(1)

plt.pcolor(x, y, z, 
           cmap='RdBu', 
           vmin=z.min(), 
           vmax=z.max())

plt.colorbar()

plt.show()
../_images/4d7c34c1479389f2a9a686f3185cb4740d54024ff03d4ebbb1b3b2b932cf95ef.png
# use 3D axis
from mpl_toolkits.mplot3d import axes3d, Axes3D

# define some z(x,y) data
def f(x, y):
    return np.sin(np.sqrt(x**2 + y**2))

x = np.linspace(-6, 6, 30)
y = np.linspace(-6, 6, 30)

xGrid, yGrid = np.meshgrid(x, y)
z = f(xGrid, yGrid)

# plot it in 3D projection
plt.figure(1)

ax = plt.axes(projection='3d')

ax.contour3D(xGrid, yGrid, z,    # Note: here we need to use xGrid & yGrid !!!
             levels=40, 
             cmap='Reds')

plt.show()
../_images/8e457f5d5d7718724060253e215bab07d46787cfa86bbbc338c87d2cf8efa960.png

plot z(x,y) from xyz files using interpolation:#

# we use Scipy's griddata function to interpolate 3D datafrom scipy.interpolate import griddata
from scipy.interpolate import griddata

# load xyz data
x, y, z = np.genfromtxt('./data/04_xyz.dat', unpack=True)

# define new x/y grids including corresponding meshgrid
xNew = np.linspace(-6, 6, 100)
yNew = np.linspace(-6, 6, 100)
xGrid, yGrid = np.meshgrid(xNew, yNew)

# and interpolate raw z(x,y) to zNew(xNew,yNew)
zNew = griddata((x, y), z, 
                (xGrid, yGrid), 
                method='nearest')

# plot color map
plt.figure(1)

plt.contourf(xGrid, yGrid, zNew, 
             levels=100,
             cmap='seismic')

#plt.axis('equal')

plt.show()
../_images/4f1fb566ede37723aa15502404cf9bffeef62ff5d751501e7741967b5d72d91c.png

Saving Figures#

# define some z(x,y) data
def f(x, y):
    return np.sin(np.sqrt(x ** 2 + y ** 2))

x = np.linspace(-6, 6, 30)
y = np.linspace(-6, 6, 30)

xGrid, yGrid = np.meshgrid(x, y)
z = f(xGrid, yGrid)

# plot it in 3D projection
plt.figure(1)

plt.contourf(xGrid, yGrid, z, 
             levels=100,
             cmap="Reds")

# save as *.png
plt.savefig('./data/test/02_colormap.png', dpi=60)
../_images/357dbe922e614a9ee9e23a6a7b78525c5fe028a8724e0aa5a676b0f1f9f19a9a.png
plt.figure(1)

x  = np.linspace(0, 5, 100)
plt.plot(x, x**2.0, color = 'b', label = "$y = x^2$")
plt.plot(x, x**3.0, color = 'k', label = "$y = x^3$")

plt.legend( loc = 2, fontsize = 12 )

plt.savefig('./data/test/03_1D.pdf')
../_images/31110077d0235e0dfabdcf4446961871601bb699f3f2c546caea692c88f604f4.png