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.
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()
In [ ]: