Unit cells are useful in materials science and engineering to show crystallographic planes and crystallographic directions. In this post, we will use Matplotlib and Python to build unit cells. Then we will will add crystallographic planes and crystallographic directions to our unit cell. Finally, we will break out the unit cell, plane and direction drawing into a function that can be used reproducibly.

Import Matplotlib

Before we start building the unit cell, we need to import Matplotlib. Matplotlib's pyplot library is typically imported with the alias plt.


In [4]:
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from matplotlib.collections import PatchCollection
import matplotlib.lines as lines

In [5]:
fig, ax = plt.subplots()
patches = []                 # empty list to store our patch objects
# add a rectangle (square)
sqr1 = mpatches.Rectangle((0,0), 5, 5,)  # xy, width, height,
patches.append(sqr1)
sqr2 = mpatches.Rectangle((-2.5,-2.5), 5, 5,)  # xy, width, height,
patches.append(sqr2)
pc = PatchCollection(patches, facecolor='w', edgecolor='k', alpha=0.1)
ax.add_collection(pc)

line1 = [(0,0), (1,0)]
line2 = [(0,0), (0,1)]

# Note that the Line2D takes a list of x values and a list of y values,
# not 2 points as one might expect.  So we have to convert our points
# an x-list and a y-list.
(line1_xs, line1_ys) = zip(*line1)
(line2_xs, line2_ys) = zip(*line2)

ax.add_line(Line2D(line1_xs, line1_ys, linewidth=2, color='blue'))
ax.add_line(Line2D(line2_xs, line2_ys, linewidth=2, color='red'))

ax.set_xlim([-10,10])
ax.set_ylim([-10,10])
ax.set_aspect('equal')
plt.show()


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-5-6f878a303855> in <module>
     18 (line2_xs, line2_ys) = zip(*line2)
     19 
---> 20 ax.add_line(Line2D(line1_xs, line1_ys, linewidth=2, color='blue'))
     21 ax.add_line(Line2D(line2_xs, line2_ys, linewidth=2, color='red'))
     22 

NameError: name 'Line2D' is not defined

In [ ]: