---
title: Tutorial 35 G-code Visualization
description: Seeing what you wrote before printing.
---
Tutorial 35 G-code Visualization
1. Lesson Header
- Lesson Number: 35
- Level: Advanced
- Title: G-code Visualization
- Estimated Duration: 50 Minutes
- Prerequisites: Lesson 29 (Parsing), Basic Graphics (Matplotlib/Three.js)
- What You Will Build: A "G-code Viewer" Script.
2. Concept Introduction
Trust but Verify.
Writing G-code manually is error-prone.
Did you move Z up? Did you close the loop?
Visualization converts the text file back into a 3D path you can inspect.
Tools:
- Online: ncviewer.com, gcode.ws.
- Offline: Cura, PrusaSlicer.
- Custom: Your own script!
3. Machine State Explanation
The Plotter.
To visualize, we need to track (X, Y, Z) over time.
Every G1 command adds a line segment to our list of segments.G0 (Travel) is usually drawn in a different color (Blue/Red) to distinguish it from printing (Extrusion).
4. Command Breakdown
- Matplotlib (Python):
plot(x_list, y_list, z_list). - Line Collection: Efficiently drawing thousands of segments.
5. Minimal Working Example
The Simple Plot.
Parse:G1 X10 Y10 -> segments.append(((0,0), (10,10)))
Plot:plt.plot(segments)
6. Visual Representation
Interactive preview is available in the interactive reader.
7. Build Exercise
Task: Write a Python script using matplotlib to visualize a G-code file in 3D.
Features:
- Parse G0, G1, G28.
- Differentiate Extrusion (Black) vs Travel (Red).
- Show Start (Green Dot) and End (Red Dot).
Algorithm:
1. Initialize current_pos = (0,0,0).
2. Loop through lines.
3. Update current_pos based on X, Y, Z args.
4. Store segment (prev_pos, current_pos, type).
5. Plot.
8. Deep Insight Section
Arc Visualization (G2/G3).
This is the hardest part.
Most simple viewers just draw a straight line for arcs.
To do it right, you must:
1. Calculate Center (I, J).
2. Calculate Start/End Angles.
3. Generate intermediate points along the arc.
4. Plot those points.
9. Common Failure Modes
- Relative Mode (G91): If your parser ignores
G91, the visualization will be completely wrong (flying off into space). You MUST track the mode state. - Performance: Matplotlib is slow for >10,000 lines. For real prints (1M lines), you need OpenGL (pyglet, three.js).
10. Real-World Application
Simulation.
CNC machines use "Verification Software" (Vericut) that simulates material removal.
It starts with a solid block and subtracts volume where the tool moves.
This detects crashes and gouges before cutting expensive metal.
11. Final Clean Version
The Viewer Script:
import matplotlib.pyplot as plt
filename = "test.gcode"
x, y, z = [0], [0], [0] # Path history
current_x, current_y, current_z = 0, 0, 0
relative_mode = False
with open(filename, 'r') as f:
for line in f:
line = line.strip().upper()
if line.startswith("G90"): relative_mode = False
if line.startswith("G91"): relative_mode = True
if line.startswith("G0") or line.startswith("G1"):
parts = line.split()
# Simplified parsing (doesn't handle all edge cases)
new_x, new_y, new_z = current_x, current_y, current_z
for part in parts:
if part.startswith("X"):
val = float(part[1:])
new_x = (current_x + val) if relative_mode else val
if part.startswith("Y"):
val = float(part[1:])
new_y = (current_y + val) if relative_mode else val
if part.startswith("Z"):
val = float(part[1:])
new_z = (current_z + val) if relative_mode else val
x.append(new_x)
y.append(new_y)
z.append(new_z)
current_x, current_y, current_z = new_x, new_y, new_z
# Plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot(x, y, z, label='Toolpath')
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
plt.show()
12. Stretch Challenge
Challenge: Add Color Gradient by Height.
Color the lines based on their Z coordinate (Blue = Bottom, Red = Top).
This helps visualize layers clearly.
Hint: Use LineCollection with a colormap.