How to Plot CFD and FEA Results with Python Matplotlib (Mesh Study and Validation)

Every CFD, FEA or experimental project ends with graphs, and in the viva they are what examiners look at first. Yet many reports still use blurry screenshots or default Excel charts. In this tutorial you will learn how to plot engineering results with Python and Matplotlib: a mesh independence study and a validation plot against a standard correlation – the two graphs almost every simulation report needs.

Quick answer: Read your exported results with pandas.read_csv, plot them with Matplotlib, label every axis with units, and save with plt.savefig(“figure.png”, dpi=300, bbox_inches=”tight”). For a mesh study, plot the key result against the number of elements and choose the mesh where further refinement changes it by less than 1%. For validation, plot your results against a correlation with a ±10% band.

The Two Graphs Every Simulation Report Needs

  • Mesh independence study – proves your answer does not depend on the mesh.
  • Validation plot – proves your model gives believable results, by comparing it with a correlation, published data or an experiment.

Our example is turbulent flow of water in a heated pipe, where the key result is the Nusselt number (Nu). The numbers in the code are sample values chosen to look like a typical study – replace them with your own exported results.

Step 1: Get Your Data into Python

Most simulation and data-logging software can export results as CSV. Put the values in two columns – for example elements,Nu – and load them with one line:

mesh = pd.read_csv("mesh_study.csv")

In the full code below the data is typed in directly, so the script runs as it is.

Step 2: The Python Code

You need NumPy, pandas and Matplotlib (pip install numpy pandas matplotlib).

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# Report-quality defaults: readable fonts, light grid, high resolution
plt.rcParams.update({
    "font.size": 11, "axes.labelsize": 12, "axes.titlesize": 12,
    "axes.grid": True, "grid.alpha": 0.3, "savefig.dpi": 300,
})

# --- 1. Mesh independence study (Re = 10 000) -----------------------
# Sample values: replace with your own, e.g. mesh = pd.read_csv("mesh_study.csv")
mesh = pd.DataFrame({
    "elements": [12_000, 25_000, 50_000, 100_000, 200_000, 400_000],
    "Nu":       [74.9,   80.3,   82.9,   84.2,    84.6,    84.7],
})
mesh["change_%"] = mesh["Nu"].pct_change().abs() * 100

# Choose the first mesh where the next refinement changes Nu by less than 1 %
next_change = mesh["change_%"].shift(-1)
chosen = mesh.loc[next_change < 1.0].iloc[0]
print(mesh.round(2).to_string(index=False))
print(f"Selected mesh: {chosen.elements:,.0f} elements (Nu = {chosen.Nu})")

# --- 2. Simulation vs correlation -----------------------------------
Pr = 7.0  # water near room temperature
cfd = pd.DataFrame({
    "Re": [5000, 10000, 15000, 20000, 25000, 30000],
    "Nu_cfd": [47.9, 84.2, 113.0, 142.6, 167.9, 194.5],
})
cfd["Nu_db"] = 0.023 * cfd["Re"]**0.8 * Pr**0.4          # Dittus–Boelter
cfd["error_%"] = (cfd["Nu_cfd"] - cfd["Nu_db"]) / cfd["Nu_db"] * 100
print(cfd.round(1).to_string(index=False))
print(f"Maximum deviation: {cfd['error_%'].abs().max():.1f} %")

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11, 4.2))

ax1.semilogx(mesh["elements"], mesh["Nu"], "o-", color="tab:blue")
ax1.plot(chosen.elements, chosen.Nu, "o", ms=12, mfc="none", mec="tab:red", mew=2,
         label=f"Selected mesh ({chosen.elements/1000:.0f}k)")
ax1.set_xticks(mesh["elements"])
ax1.set_xticklabels([f"{e // 1000}k" for e in mesh["elements"]])
ax1.minorticks_off()
ax1.set_xlabel("Number of elements")
ax1.set_ylabel("Nusselt number, Nu")
ax1.set_title("Mesh independence study")
ax1.legend(loc="lower right")

Re_line = np.linspace(4000, 31000, 200)
Nu_line = 0.023 * Re_line**0.8 * Pr**0.4
ax2.fill_between(Re_line, 0.9 * Nu_line, 1.1 * Nu_line, color="tab:gray", alpha=0.2,
                 label="±10 % band")
ax2.plot(Re_line, Nu_line, "-", color="tab:gray", label="Dittus–Boelter")
ax2.plot(cfd["Re"], cfd["Nu_cfd"], "s", color="tab:orange", label="CFD results")
ax2.set_xlabel("Reynolds number, Re")
ax2.set_title("Validation against correlation")
ax2.legend(loc="upper left")

plt.tight_layout()
plt.savefig("cfd_results.png", bbox_inches="tight")   # use .pdf or .svg for vector output
plt.show()

Step 3: The Results

 elements   Nu  change_%
    12000 74.9       NaN
    25000 80.3      7.21
    50000 82.9      3.24
   100000 84.2      1.57
   200000 84.6      0.48
   400000 84.7      0.12
Selected mesh: 100,000 elements (Nu = 84.2)
   Re  Nu_cfd  Nu_db  error_%
 5000    47.9   45.6      5.0
10000    84.2   79.4      6.1
15000   113.0  109.8      2.9
20000   142.6  138.2      3.2
25000   167.9  165.2      1.6
30000   194.5  191.2      1.7
Maximum deviation: 6.1 %
Mesh independence study and CFD validation plot made with Python Matplotlib
Mesh independence study (left) and validation against the Dittus–Boelter correlation (right), plotted with Matplotlib.

How to Read These Graphs

  • Mesh study: Nu rises quickly at first and then levels off. Going from 100k to 200k elements changes Nu by only 0.48%, so the 100k mesh is chosen – a finer mesh would cost much more computing time for almost no change.
  • Validation: all CFD points lie inside the ±10% band of the Dittus–Boelter correlation, with a maximum deviation of 6.1%. Since the correlation itself has an uncertainty of around this level, this is good agreement.
  • Write one sentence for each graph in your report saying exactly this. Examiners want the conclusion, not only the picture.

Six Tips for Report-Quality Graphs

  1. Units on every axis – “Temperature (°C)”, not “Temp”.
  2. Use a log scale when values span orders of magnitude, like element counts – and set readable tick labels such as 12k, 25k, 50k.
  3. Markers for data, lines for theory – readers can tell measured or simulated points from equations at a glance.
  4. Save at 300 dpi or as PDF/SVG – never paste a screenshot.
  5. One style for the whole report – set rcParams once at the top so every figure matches.
  6. Keep the script – when your results change the night before submission, you rerun it and every graph updates.

Try It Yourself

  1. Replace the sample values with results from your own project.
  2. Add experimental data with error bars using plt.errorbar.
  3. Compare several design cases on one graph – for example plain tube vs twisted tape.
  4. Compute the Grid Convergence Index (GCI) for a more formal mesh study.

For more worked examples, see beam deflection in Python and heat exchanger design in Python (LMTD method), or browse our CFD projects.

Learn Python for Mechanical Engineering

In our Python for mechanical engineers classes you learn NumPy, pandas and Matplotlib through engineering problems, in live screen-share sessions or recorded videos, and write the code for your own project yourself. We also guide you on how to present your results and structure your report – start with our free report and PPT templates.

Frequently Asked Questions

How do I plot CFD or FEA results in Python?

Export the results from your simulation software as a CSV file, read it with pandas.read_csv, and plot the columns with Matplotlib. Set labels with units, a title and a legend, then save the figure with savefig at 300 dpi or as a PDF or SVG.

What is a mesh independence study?

It is a check that your simulation result does not depend on the mesh size. You solve the same case on several meshes, plot a key result such as Nusselt number or maximum stress against the number of elements, and choose the mesh beyond which further refinement changes the result by less than about 1 to 2 percent.

How do I validate CFD results with a correlation?

Compare your simulation results with an accepted empirical correlation, such as Dittus–Boelter for turbulent flow in a pipe, across the range of Reynolds numbers you studied. Plot both with an error band and report the maximum deviation.

What dpi should I use for graphs in a project report or paper?

Use at least 300 dpi for PNG images in reports and journal papers. Vector formats such as PDF or SVG stay sharp at any size and are preferred by many journals.

Why is Matplotlib better than Excel for engineering graphs?

Matplotlib graphs are reproducible – when your results change, you run the script again and every figure updates with the same style. It also handles log scales, error bands, many data sets and publication-quality output more easily than Excel.

Start Learning

Tell us your project and the graphs you need to make. Message us on WhatsApp or use the enquiry form on our home page.

Interested in this project? Get the details, files and guidance from our team.

Enquire on WhatsApp

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top