ThisCalculator

Everyday

Draw Quantum Circuit Diagrams with Python and Matplotlib

Updated · Standard formula, shown below

Python and Matplotlib can turn a small set of qubits and operations into a clean, publication-ready quantum circuit diagram. You will draw wires, gates, labels, and connections directly, so the result is easy to customize without relying on a quantum simulator.

What You’ll Need

  • Python 3 and Matplotlib installed in the same environment. Install Matplotlib with python -m pip install matplotlib if needed.
  • A Python editor or notebook, such as a terminal-based script or Jupyter notebook.
  • A circuit layout plan: decide how many wires you need and which operation belongs at each position.

Step-by-Step

  1. Plan the circuit as a grid. Treat each qubit wire as a horizontal row and each operation position as a column. For example, a two-qubit circuit with a Hadamard on the first qubit followed by a controlled-NOT uses two rows and two operation columns. This layout makes spacing predictable and keeps gates aligned.
  2. Import Matplotlib and create a figure. Start with a script containing these imports:
    import matplotlib.pyplot as plt
    from matplotlib.patches import Rectangle, Circle

    Create a figure and axes with fig, ax = plt.subplots(figsize=(7, 2.5)). The figure size is in inches; make it wider for more operations and taller for more wires.

  3. Set coordinate conventions. Use increasing x values from left to right for time, and increasing y values from the bottom wire upward. One practical choice is to place wire 0 at y=1, wire 1 at y=0, and so on. Keep this convention consistent when labeling qubits and adding gates.
  4. Draw the qubit wires. For two wires at y=0 and y=1, draw thin horizontal lines across the circuit area:
    wire_y = [1, 0]
    for y in wire_y:
        ax.plot([0, 4], [y, y], color="black", linewidth=1)

    The x range from 0 to 4 provides room for gates. Extend the lines slightly past the first and last gates for a balanced appearance.

  5. Add wire labels. Place labels just left of the lines using ax.text(-0.25, y, rf"$q_{i}$", ha="right", va="center") inside a loop over the wire indices. You can use |0⟩ labels for input states if appropriate, but distinguish initial-state notation from the wire’s qubit name.
  6. Draw a single-qubit gate. A gate is usually a small rectangle centered on its wire. For example, at x=1.2 on the top wire, use Rectangle((0.95, 0.8), 0.5, 0.4), add it to the axes with ax.add_patch(...), then put an H label at (1.2, 1). The rectangle’s lower-left corner is its center minus half its width and height. Choose a white fill so the wire does not show through the gate.
  7. Draw a controlled gate. For a CNOT with control on the top wire and target on the bottom wire, draw a vertical connector at the gate’s x coordinate. Add a filled control dot with a small Circle at the control wire. At the target, draw a circle outline and two short crossing lines to make a plus sign. Use the same x coordinate for the connector and both symbols.
  8. Add operation labels and spacing. Place gate centers at regular x intervals, such as 1.2, 2.4, and 3.6. Keep enough horizontal space for long labels and enough vertical space for multi-qubit connectors. If gates overlap, increase the figure width or the distance between operation columns rather than shrinking every gate.
  9. Set limits, aspect, and ticks. Hide axes decorations and leave a margin around the drawing:
    ax.set_xlim(-0.6, 4.3)
    ax.set_ylim(-0.5, 1.5)
    ax.set_aspect("equal")
    ax.axis("off")

    Equal aspect keeps circles round. Adjust limits if labels or gate edges are clipped; do not rely on the default plotting bounds.

  10. Save or display the diagram. Call fig.tight_layout(), then save with fig.savefig("circuit.png", dpi=200, bbox_inches="tight"). For crisp text in papers, use a vector format such as fig.savefig("circuit.pdf", bbox_inches="tight"). Use plt.show() when you also want to view the diagram interactively.

Common Mistakes

  • Mixing up wire order: Decide whether qubit 0 is the top or bottom wire and use that choice everywhere. A reversed convention can make a correct-looking drawing describe the wrong circuit.
  • Placing labels at the wrong coordinates: Text anchors are positioned at the coordinates you provide. Use ha and va alignment options to control how labels sit relative to those points.
  • Forgetting that a gate covers its wire: If a rectangle has no opaque face color, the wire may remain visible through it. Set a face color and edge color explicitly.
  • Using unequal aspect accidentally: Without ax.set_aspect("equal"), target circles can appear oval and connector geometry can look distorted.
  • Saving before setting limits: Automatic limits can crop or crowd labels, particularly labels placed outside the wire area. Set limits after adding all circuit elements.

Tips

  • Write small helper functions such as draw_wire, draw_gate, and draw_controlled_x if you need to make several diagrams. Pass coordinates as arguments so the functions can be reused.
  • Keep layout data separate from drawing commands. A list of gate names, wire indices, and x positions makes it easier to change the circuit without rewriting the plotting code.
  • Use consistent gate dimensions, line widths, and font sizes. A small number of visual rules makes a diagram easier to scan.
  • For a barrier, measurement symbol, swap gate, or multi-control operation, create a dedicated drawing function and test it on a simple circuit before combining it with other elements.
  • Use PDF or SVG for scalable output when the destination supports vector graphics. PNG is useful for documents and web pages that need a raster image.

Troubleshooting

The diagram is blank: Check that you added artists to the same axes object you display or save, and that the coordinates fall within the axis limits. In a script, call plt.show() to open an interactive window.

Labels or gates are cut off: Expand set_xlim or set_ylim, then save again with bbox_inches="tight". Remember that tight bounding boxes help with saving but do not fix labels positioned outside the visible axes during interactive display.

Matplotlib cannot be imported: Install it in the Python environment running your script. If several Python installations are present, run python -m pip install matplotlib using the same interpreter you use to launch the program.

The drawing looks cramped: Increase figsize, move operation columns farther apart, or reduce label length. If the image is only low-resolution rather than cramped, raise the PNG dpi value.

Frequently Asked Questions

Do I need a quantum computing library?
No. Matplotlib can draw a schematic using ordinary shapes and text. A quantum library is useful when you also want to build, simulate, or export circuits in a specific notation.

How do I draw a measurement?
Draw a meter-like symbol or labeled box on the relevant wire and add a classical output line or label if your diagram needs to show the result. Use a consistent visual convention and explain unusual symbols.

Can I use LaTeX in gate labels?
Yes. Matplotlib supports math-text strings such as r"$R_z(\theta)$". For full LaTeX rendering, additional system software may be required; math-text is simpler for common symbols.

How can I show a barrier or gate spanning several wires?
Draw a vertical line for a barrier, or a single rectangle extending across the selected wires for a grouped operation. Make its meaning clear with a label or caption.

Which file format should I choose?
Use PDF or SVG for scalable vector output and PNG when a raster image is required. Check that fonts and symbols render correctly in the application where the figure will be used.

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.