How to Plot Stacked XRD Patterns in Python: From Raw Files to a 600-dpi Figure
A tested, downloadable Matplotlib script for stacked XRD patterns: load Bruker, Rigaku and PANalytical exports, normalise, smooth safely, add reference sticks and (hkl) labels, zoom on peak shifts and export a 600-dpi TIFF.
Quick answer: Export your patterns as two-column text, cut them to a common 2θ range, subtract the minimum and divide by the strongest peak, then add a constant vertical offset per sample. Draw reference positions as short sticks underneath, and size the figure to the journal column (90 mm) before you export. The complete, tested script is free to download below.
Download stacked_xrd.py (needs Python 3.9+, numpy, matplotlib; scipy only if you turn on smoothing). Edit the settings block at the top and run python stacked_xrd.py.

Output of the script with synthetic demo data. The inset overlays the (111) peak of all three samples, which makes the narrowing at higher temperature (crystallite growth) visible. In the stacked view you can’t see it.
What this guide solves
| Problem | Section |
|---|---|
| ”My XRD file won’t load” (binary formats, decimal commas, headers) | Step 1 |
| Patterns overlap or one sample looks flat | Step 2 |
| Noisy data, and whether smoothing is allowed | Step 3 |
| Where to get reference peak positions and intensities without a paid card | Step 4 |
| Peak shifts that are invisible in a stacked plot | Step 5 |
| ”Resolution too low” from the submission system | Step 6 |
Step 1: Get the data out of the instrument
The script reads any text file with 2θ and intensity in the first two columns, and skips header lines automatically. The problem is usually the file format, not Python:
| Instrument / software | Typical file | What to do |
|---|---|---|
| Bruker (DIFFRAC) | .raw, .brml (binary/zip) | In DIFFRAC.EVA: File → Export → .xy / .txt |
| Rigaku (SmartLab, MiniFlex) | .ras, .txt | .ras is text; it loads directly |
| Malvern Panalytical | .xrdml (XML) | In HighScore: File → Save as → .xy, or convert with a format converter such as PowDLL |
| Any software, European locale | 43,316;1520 | Decimal commas are handled when the separator is ; or tab |
If you see No numeric data in …, the file is binary. Export it as .xy first.
The loader in the script:
def load_xrd(path):
rows = []
with open(path, encoding="utf-8", errors="ignore") as f:
for line in f:
s = line.strip()
if ";" in s or "\t" in s: # decimal commas are only safe here
s = re.sub(r"(\d),(\d)", r"\1.\2", s)
parts = re.split(r"[,;\s]+", s)
try:
rows.append([float(parts[0]), float(parts[1])])
except (ValueError, IndexError):
continue # header, units or comment line
data = np.array(rows)
order = np.argsort(data[:, 0]) # some exports are descending
return data[order, 0], data[order, 1]
Step 2: Normalise and offset, but choose deliberately
x, y = x[(x >= 25) & (x <= 85)], y[(x >= 25) & (x <= 85)] # same range for all samples
y = y - y.min() # baseline to zero
y = y / y.max() # strongest peak = 1
ax.plot(x, y + 0.7 + i * 1.1) # constant offset per sample
Normalising changes what the figure can show. Pick the option that matches your claim:
| You want to show… | Use | Write in the caption |
|---|---|---|
| Phase identification, new or vanishing peaks | Normalise to max + offset | ”normalised to the most intense reflection” |
| Peak shifts or relative intensity changes | Normalise + an overlaid inset (Step 5) | the same |
| Crystallinity increase, amorphous fraction | Don’t normalise, plot counts on the same scale | ”measured under identical conditions” |
| Texture or preferred orientation | Normalise; compare I(111)/I(200) ratios in a table | the ratios |
Two rules prevent most messy stacks:
- Cut every pattern to the same 2θ range before normalising. Otherwise a strong low-angle peak or an amorphous hump below 20° can flatten one sample.
- Use a constant offset (
i * spacing), not values tuned by hand, so that adding a fourth sample during revision takes one line.
Step 3: Smoothing — for display only
Set SMOOTH = 11 in the script to apply a Savitzky–Golay filter (window 11 points, 3rd-order polynomial). It removes counting noise while keeping peak positions and shapes far better than a moving average.
- Don’t smooth data that you use for FWHM, Scherrer or Williamson–Hall analysis. Smoothing broadens peaks and inflates the apparent strain. Do the analysis on the raw data and smooth only the plot.
- If the noise is really bad, a longer counting time per step helps more than any filter.
- Mention it in the Experimental section: “XRD patterns are shown after Savitzky–Golay smoothing for clarity.”
Step 4: Reference peaks — positions and intensities without a paid card
Positions follow from Bragg’s law. For a cubic phase, d = a / √(h² + k² + l²) and 2θ = 2 arcsin(λ / 2d):
def bragg_2theta(a, hkl, wavelength=1.5406): # Cu Kα1
d = a / math.sqrt(sum(i * i for i in hkl))
s = wavelength / (2 * d)
return 2 * math.degrees(math.asin(s)) if s <= 1 else None # None = not reachable
Only some (hkl) appear, depending on the lattice:
| Lattice | Allowed reflections | First peaks | Examples |
|---|---|---|---|
| fcc | h, k, l all odd or all even | (111), (200), (220), (311) | Cu, Ag, Au, Al, Ni |
| bcc | h + k + l even | (110), (200), (211) | α-Fe, W, Mo |
| diamond | fcc rule, and not h + k + l = 4n + 2 | (111), (220), (311) | Si, Ge |
| simple cubic | all | (100), (110), (111) | — |
Intensities aren’t given by Bragg’s law; they depend on atom positions. Free ways to get them:
- COD (Crystallography Open Database) gives a free CIF file for most common phases.
- VESTA (free) opens the CIF and simulates the powder pattern under Utilities → Powder Diffraction Pattern.
- Materials Project shows a calculated XRD pattern for each structure.
- pymatgen calculates the pattern in Python from the CIF (
pip install pymatgen):
from pymatgen.core import Structure
from pymatgen.analysis.diffraction.xrd import XRDCalculator
structure = Structure.from_file("Cu.cif") # e.g. downloaded from COD
pattern = XRDCalculator(wavelength="CuKa").get_pattern(structure, two_theta_range=(20, 90))
for tt, inten, hkls in zip(pattern.x, pattern.y, pattern.hkls):
print(f"{tt:7.3f} {inten:6.1f} {hkls[0]['hkl']}")
For Cu this prints 43.35° (111) 100, 50.49° (200) 47 and 74.20° (220) 27. "CuKa" is the Kα1/Kα2 average; use wavelength="CuKa1" to match the Kα1 positions used in the rest of the script. Put the result into REF_PEAKS in the script. If you do have an ICDD card, quote its number (e.g. “PDF#04-0836”) in the caption.
Step 5: Make peak shifts visible with an inset
A shift of 0.1–0.3° (lattice expansion, doping, residual stress) is invisible in a 60°-wide stacked plot. The script draws an inset that overlays (not stacks) a narrow window of every pattern:
INSET = (42.0, 44.5) # 2θ window around the (111) peak; None to disable
The inset sits in the empty space above the top pattern. In the example it shows a peak getting narrower rather than shifting, which is just as important to show.
Before you interpret a shift, check:
- Sample height displacement shifts every peak, in a way that varies smoothly with angle. Use an internal standard (Si powder) if the effect matters.
- Kα2 shoulders at high angle look like peak splitting. Strip Kα2 in the instrument software, or say that both are present.
- Compare positions from peak fitting, not from the maximum data point. See XRD peak fitting.
Step 6: Export so it passes the journal check
fig, ax = plt.subplots(figsize=(90 / 25.4, 85 / 25.4), layout="constrained") # 90 mm wide
...
fig.savefig("xrd_stacked.png", dpi=600, facecolor="white")
Image.open("xrd_stacked.png").convert("RGB").save(
"xrd_stacked.tiff", compression="tiff_lzw", dpi=(600, 600))
Two easy-to-miss details:
- Don’t use
bbox_inches="tight"for the final file. It trims the margins, so a “90 mm, 600 dpi” figure comes out about 79 mm wide. When it is enlarged back to column width, the real resolution drops to about 530 dpi and the submission check fails. Uselayout="constrained"instead. - Matplotlib saves RGBA. Some systems reject transparent images. The script converts the TIFF to RGB.
Check any image with check_figure.py, explained in journal figure size and DPI.
Troubleshooting
| Symptom | Cause | Fix |
|---|---|---|
No numeric data in … | Binary file (.raw, .brml, .xrdml) | Export as .xy / .txt (Step 1) |
| Values ten times too large | Decimal comma with comma separators | Export with ; or tab separators |
| One pattern looks flat | Different 2θ range, or an outlier spike | Crop all samples to the same range; check for detector spikes |
math domain error | Reflection beyond 2θ = 180° | Already handled: the function returns None |
| Labels overlap the inset | Strong peak under the inset | Move the inset: ax.inset_axes([x0, y0, w, h]) |
| Squares instead of θ or ° | Font has no glyph | Keep "DejaVu Sans" as a fallback in font.family |
| Figure looks fine on screen, tiny in print | Drawn too big, then shrunk | Set FIG_SIZE_MM to the column width |
Pre-submission checklist
- Same 2θ range, same normalisation and the same sample order in every XRD figure.
- The y-axis reads “Intensity (a.u.)” without tick numbers when the patterns are normalised and offset.
- The caption names the reference (card number or CIF source) and says how intensities were scaled.
- Smoothing, if any, is stated, and the analysis was done on the raw data.
- The file is 90 or 190 mm wide, RGB, 600 dpi or more (1000 dpi for Elsevier line art).
Next: Scherrer and Williamson–Hall crystallite size. No-code alternative: Spectra Studio (free Windows app).
Need more figure types with the same quality? The MatSci Figure Kit builds on this script with:
- phase markers (▼ Cu₂O …) and Bragg reflections for fcc, bcc, diamond and wurtzite lattices
- Scherrer size
- journal presets for Elsevier, ACS, RSC and Wiley
- nine more ready-to-edit scripts, including FTIR and Raman with peak labels, DSC/TMA, particle-size distribution with D10/D50/D90, and multi-panel (a)–(f) figures
Related Posts
Error Bars and Bar Charts in Materials Papers: SD, SEM or 95% CI, and What n Really Means
What reviewers expect from error bars: when to use standard deviation, standard error or confidence intervals, how to count n for specimens and measurements, why to show individual data points, and how to write it in captions, with a free plotting tool.
Journal Figure Size and DPI: How to Fix "Resolution Too Low" for Good
Column widths, pixel targets and font sizes for Elsevier, ACS, RSC, Wiley and Springer, why changing the DPI number does nothing, and how to export correctly from Python, Origin, Excel and Word.
How to Standardize Spectroscopy Figures for a Paper
Build consistent XRD, FTIR, Raman, and UV-Vis figures with repeatable offsets, fonts, axes, and export settings instead of reformatting every plot.