Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Matplotlib

What is Matplotlib?

Matplotlib is Python’s most popular plotting library for visualization and data analysis. It creates publication-quality figures and supports integration with NumPy, making it the standard choice for scientific computing in Python.

Why Matplotlib is Essential for This Course

Throughout this course, you’ll use Matplotlib to:

  • Visualize crystal structures

  • Plot materials properties (band gaps, bulk moduli, elastic tensors)

  • Display computational results (energy landscapes, phase diagrams)

  • Analyze data from Materials Project and other sources

Basic Plotting

Simple Line Plot

import matplotlib.pyplot as plt
import numpy as np

# Generate data
x = np.linspace(0, 10, 100)
y = np.sin(x)

# Create figure and plot
plt.figure(figsize=(8, 4))
plt.plot(x, y, label='Sine Wave')
plt.xlabel('x (radians)')
plt.ylabel('sin(x)')
plt.title('Simple Sine Wave')
plt.grid(True)
plt.legend()
plt.show()
<Figure size 800x400 with 1 Axes>

Scatter Plot

# Example data
materials = ['Al', 'Cu', 'Fe', 'Ti']
bulk_moduli = [89, 130, 200, 120]
densities = [2.70, 8.96, 7.87, 4.51]

plt.figure(figsize=(8, 4))
plt.scatter(densities, bulk_moduli)

# Add labels
for i, mat in enumerate(materials):
    plt.annotate(mat, (densities[i], bulk_moduli[i]), 
                xytext=(5, 5), textcoords='offset points')

plt.xlabel('Density (g/cm³)')
plt.ylabel('Bulk Modulus (GPa)')
plt.title('Bulk Modulus vs Density by Material')
plt.grid(True)
plt.show()
<Figure size 800x400 with 1 Axes>

Histogram

# Generate random data
data = np.random.normal(100, 1.0, 1000)

plt.figure(figsize=(8, 4))
plt.hist(data, bins=30, edgecolor='black', alpha=0.7, color='skyblue')
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.title('Distribution of Bulk Moduli')
plt.grid(axis='y', alpha=0.3)
plt.show()
<Figure size 800x400 with 1 Axes>

Customization

Subplots

fig, axes = plt.subplots(2, 2, figsize=(12, 8))

# Plot 1: Bulk modulus vs. density
axes[0, 0].scatter(densities, bulk_moduli, color='steelblue')
axes[0, 0].set_xlabel('Density (g/cm³)')
axes[0, 0].set_ylabel('Bulk Modulus (GPa)')
axes[0, 0].set_title('Bulk Modulus vs. Density')
axes[0, 0].grid(True)

# Plot 2: Another simple plot
axes[0, 1].plot(x, np.cos(x), color='darkorange', linewidth=2)
axes[0, 1].set_xlabel('x')
axes[0, 1].set_ylabel('cos(x)')
axes[0, 1].set_title('Cosine Wave')
axes[0, 1].grid(True)

# Plot 3: Histogram
axes[1, 0].hist(data, bins=20, edgecolor='black', alpha=0.6)
axes[1, 0].set_xlabel('Value')
axes[1, 0].set_ylabel('Frequency')
axes[1, 0].set_title('Data Distribution')
axes[1, 0].grid(axis='y', alpha=0.3)

# Plot 4: Bar chart
categories = ['Mechanical', 'Thermal', 'Electronic', 'Magnetic']
values = [85, 90, 75, 80]
axes[1, 1].bar(categories, values, color=['steelblue', 'darkorange', 'forestgreen', 'crimson'])
axes[1, 1].set_ylabel('Value (arbitrary units)')
axes[1, 1].set_title('Material Properties Comparison')
axes[1, 1].grid(axis='y', alpha=0.3)

fig.tight_layout()
plt.show()
<Figure size 1200x800 with 4 Axes>

Saving Figures

Format for Publications

# Create a simple plot to save
plt.figure(figsize=(8, 4), dpi=300)
plt.plot(densities, bulk_moduli, 'o-', linewidth=2, markersize=8)
plt.xlabel('Density (g/cm³)')
plt.ylabel('Bulk Modulus (GPa)')
plt.title('Bulk Modulus vs Density')
plt.grid(True, alpha=0.3)
plt.tight_layout()

# Save as PNG
plt.savefig('bulk_modulus_vs_density.png', dpi=300)
print("Saved as PNG")

# Save as PDF (vector graphics)
plt.savefig('bulk_modulus_vs_density.pdf', format='pdf', bbox_inches='tight')
print("Saved as PDF")

plt.show()
Saved as PNG
Saved as PDF
<Figure size 2400x1200 with 1 Axes>

Resolution

For publications:

  • Use 300-600 DPI for raster graphics (PNG, JPG)

  • Use vector-based formats for text/equations (PDF, SVG)

  • Use bbox_inches='tight' to avoid whitespace


Common Pitfalls

  1. Forgotten plt.show(): Always call plt.show() to display plots in Jupyter notebooks

  2. Wrong figure size: Set figsize appropriately - not too small or too large

  3. Overlapping plots: Use plt.tight_layout() or adjust spacing to avoid overlap

  4. Incorrect labels: Always set xlabel, ylabel, and title on axes

  5. Not importing matplotlib: Always import matplotlib.pyplot as plt


Summary

By the end of this chapter, you should:

  • Create basic plots (line, scatter, histogram)

  • Understand figure customization (labels, titles, legends)

  • Use subplots for multi-panel figures

  • Save figures in appropriate formats

  • Know how to integrate Matplotlib with NumPy

  • Avoid common pitfalls in plot creation