Skip to content

Bloch Sphere Visualization ​

API reference for Bloch sphere visualization functions in pyqpanda3. These functions render single-qubit states and circuits as interactive or static plots on the Bloch sphere.

plot_bloch ​

Unified entry point that automatically dispatches to the appropriate Bloch visualization function based on the input type.

Signature ​

python
plot_bloch(
    state,
    title: str = '',
    figsize: Optional[tuple] = None,
    save: Optional[str] = None
)

Parameters ​

ParameterTypeDescription
statearray_like or QCircuitInput to visualize. A 3-element list/tuple dispatches to plot_bloch_vector; a longer iterable dispatches to plot_bloch_multivector; a QCircuit or QProg dispatches to plot_bloch_circuit.
titlestrPlot title (default '').
figsizetuple, optionalFigure size in inches (default (5, 5) for vector/state inputs; ignored for circuit inputs).
savestr, optionalFile path to save the output image (only effective for circuit inputs; for vector/state inputs, save the returned figure manually via fig.savefig()).

Returns ​

  • matplotlib.figure.Figure when visualizing a vector or state.
  • None when visualizing a QCircuit or QProg (animation is displayed or saved to file).

Dispatch Behavior ​

Input TypeDispatches To
list / tuple of length 3plot_bloch_vector
Any iterable (e.g., state vector)plot_bloch_multivector
QCircuit / QProgplot_bloch_circuit

Examples ​

python
from pyqpanda3.visualization import plot_bloch

# Single Bloch vector (|+> state on X axis)
plot_bloch([1, 0, 0], title="X State")

# Multi-qubit state vector
plot_bloch([1, 0, 0, 0], title="Bell-like State")

# Save to file
fig = plot_bloch([0, 0, 1], title="Z State")
fig.savefig("bloch.png")


plot_bloch_vector ​

Plot a single 3-element Bloch vector on a Bloch sphere.

Signature ​

python
plot_bloch_vector(
    bloch,
    title="bloch",
    axis_obj=None,
    fig_size=None
)

Parameters ​

ParameterTypeDescription
blocharray_likeA 3-element sequence [x, y, z] representing the Bloch vector.
titlestrPlot title (default "bloch").
axis_objmatplotlib.axes.Axes, optionalAn existing 3D axes to draw on. If None, a new figure is created.
fig_sizetuple, optionalFigure size in inches (default (5, 5)).

Returns ​

  • matplotlib.figure.Figure when axis_obj is None.
  • None when drawing onto an existing axis_obj.

Examples ​

python
from pyqpanda3.visualization import plot_bloch_vector

# |0> state (north pole)
plot_bloch_vector([0, 0, 1], title="|0> State")

# |+> state (positive X axis)
plot_bloch_vector([1, 0, 0], title="|+> State")

# |+i> state (positive Y axis)
plot_bloch_vector([0, 1, 0], title="|+i> State")


plot_bloch_multivector ​

Plot one Bloch sphere per qubit for a multi-qubit quantum state. Each sphere shows the reduced Bloch vector for that qubit computed via the partial trace.

Signature ​

python
plot_bloch_multivector(
    state,
    title='',
    fig_size=None
)

Parameters ​

ParameterTypeDescription
statearray_likeQuantum state vector. Length must be a power of 2 (e.g., 4 for 2 qubits, 8 for 3 qubits).
titlestrOverall figure title (default '').
fig_sizetuple, optionalFigure size in inches.

Returns ​

matplotlib.figure.Figure -- the figure containing all Bloch sphere subplots.

Examples ​

python
import numpy as np
from pyqpanda3.visualization import plot_bloch_multivector

# Two-qubit state: both qubits in |+> (equal superposition)
plot_bloch_multivector([0.5, 0.5, 0.5, 0.5], title="Two Qubits in |+>")

# Single qubit in |0> state
plot_bloch_multivector([1, 0], title="Single Qubit |0>")

# Bell state |00> + |11> (each qubit reduced state is maximally mixed)
plot_bloch_multivector(np.array([1, 0, 0, 1]) / np.sqrt(2), title="Bell State")


plot_bloch_circuit ​

Animate a single-qubit quantum circuit on a Bloch sphere. The state vector is updated frame-by-frame as each gate is applied, producing a smooth rotation animation.

Signature ​

python
plot_bloch_circuit(
    circuit,
    trace=True,
    saveas=None,
    fps=20,
    secs_per_gate=1
)

Parameters ​

ParameterTypeDescription
circuitQCircuit or QProgSingle-qubit quantum circuit to animate. Only supports gates: H, X, Y, Z, RX, RY, RZ, S, S†, T, T†, U1.
traceboolWhether to display the path traced by the state vector (default True).
saveasstr, optionalFile path to save the animation (e.g., 'bloch.gif'). If None, the animation is displayed interactively.
fpsintFrames per gate, controlling animation smoothness (default 20).
secs_per_gatefloatDuration in seconds for each gate's animation segment (default 1).

Returns ​

None. The animation is displayed interactively or saved to a file specified by saveas.

Supported Gates ​

GateNotes
HHadamard
X, Y, ZPauli gates
RX, RY, RZParameterized rotations (angle in radians)
S, S†Phase and inverse phase
T, T†T gate and inverse T gate
U1Single-parameter phase gate

Raises ​

  • ImportError -- if Matplotlib is not installed.
  • RuntimeError -- if the circuit is empty, contains unsupported gates, or acts on more than one qubit.

Examples ​

python
from pyqpanda3.core import QProg, H, RX, Qubit
from pyqpanda3.visualization import plot_bloch_circuit

# Simple Hadamard circuit
q = Qubit(0)
prog = QProg()
prog << H(q)

# Display interactive animation
plot_bloch_circuit(prog)

# Save animation to file
plot_bloch_circuit(prog, saveas="hadamard.gif", fps=30)

# Rotation circuit with trace
prog2 = QProg()
prog2 << RX(q, 3.14159) << H(q)
plot_bloch_circuit(prog2, trace=True, secs_per_gate=2)


Bloch (class) ​

Low-level class for building a Bloch sphere plot incrementally. Accessible via pyqpanda3.visualization.bloch.Bloch. Use this when you need finer control than the plot_bloch_* helpers provide -- e.g., adding multiple vectors, points, or annotations onto the same sphere with custom styling.

Constructor ​

python
Bloch(
    fig=None,
    axes=None,
    view=None,
    figsize=None,
    background=False
)

Constructor Parameters ​

ParameterTypeDescription
figmatplotlib.figure.Figure, optionalUser-supplied Matplotlib figure for the Bloch sphere. If None, one is created on render.
axesmatplotlib.axes.Axes, optionalUser-supplied 3D axes for Bloch sphere animation. If None, axes are created on render.
viewlist, optionalAzimuthal and elevation viewing angles [azim, elev] (default [-60, 30]).
figsizelist, optionalFigure size in inches [w, h] (default [5, 5]).
backgroundboolIf True, render the default 3D axes background instead of the bare sphere (default False).

Selected Attributes (configurable after construction) ​

AttributeDefaultDescription
sphere_color"#FFDDDD"Color of the Bloch sphere surface.
sphere_alpha0.2Transparency of the sphere surface.
frame_color"gray"Color of the wireframe.
frame_width1Width of the wireframe lines.
frame_alpha0.2Transparency of the wireframe.
font_colormatplotlib defaultColor used for axis labels.
font_size20Font size used for axis labels.
xlabel / ylabel / zlabel["$x$", ""] / ["$y$", ""] / [r"$|0\rangle$", r"$|1\rangle$"]Axis label pairs (+axis, -axis).
xlpos / ylpos / zlpos[1.2, -1.2]Label positions for each axis.
vector_color["#dc267f", "#648fff", "#fe6100", "#785ef0", "#ffb000"]Cycle of colors used for plotted vectors.
vector_width5Width of plotted vectors.
vector_style`"->"`
vector_mutation20Arrowhead size.
point_color["b", "r", "g", "#CC6600"]Cycle of colors used for plotted points.
point_size[25, 32, 35, 45]Cycle of marker sizes.
point_marker["o", "s", "d", "^"]Cycle of marker shapes.

Methods ​

MethodSignatureDescription
add_vectorsadd_vectors(vectors)Append one vector (3 elements) or a list of vectors.
add_pointsadd_points(points, meth="s")Append points; meth is "s" (single color), "m" (multicolored), or "l" (connected by line).
add_annotationadd_annotation(state_or_vector, text, **kwargs)Add a text/LaTeX annotation at a 3D position. Extra kwargs are forwarded to mpl_toolkits.mplot3d.axes3d.Axes3D.text (e.g., fontsize, color, horizontalalignment).
set_label_conventionset_label_convention(convention)Apply a preset label set. Valid values: "original", "xyz", "sx sy sz", "01", "polarization jones", "polarization jones letters", "polarization stokes".
clearclear()Reset all stored points, vectors, and annotations.
renderrender(title="")Render the sphere and all data onto the current figure and axes.
make_spheremake_sphere()Alias for render() with no title.
showshow(title="")Render the sphere and call pyplot.show().
savesave(name=None, output="png", dirc=None)Render and save to file. If name is given, it overrides output and dirc. Defaults to bloch_<n>.png in the current working directory.

Examples ​

python
from pyqpanda3.visualization.bloch import Bloch

# Build a custom Bloch sphere with two vectors and an annotation
sphere = Bloch()
sphere.add_vectors([1, 0, 0])
sphere.add_vectors([0, 0, 1])
sphere.add_annotation([0, 0, 1.2], r"$|0\rangle$")
sphere.set_label_convention("01")
sphere.save(name="two_states.png")

# Save to file
sphere2 = Bloch(view=[-30, 20], figsize=[6, 6])
sphere2.add_vectors([0, 1, 0])
sphere2.save(name="my_bloch.png")

See Also ​

Released under the MIT License.