An open-source SDK for working with quantum computers at the level of extended quantum circuits, operators, and primitives.
—
Qiskit provides comprehensive visualization tools for quantum circuits, states, measurement results, and hardware topologies. These tools enable analysis, debugging, and presentation of quantum computing results across multiple output formats.
Draw quantum circuits in multiple formats for analysis and presentation.
def circuit_drawer(circuit, output=None, scale=None, filename=None, style=None,
interactive=False, plot_barriers=True, reverse_bits=None,
justify=None, vertical_compression='medium', idle_wires=True,
with_layout=True, fold=None, ax=None, initial_state=False,
cregbundle=None, wire_order=None, expr_len=30):
"""
Draw quantum circuit.
Parameters:
- circuit: QuantumCircuit to draw
- output: Output format ('text', 'mpl', 'latex', 'latex_source')
- scale: Image scaling factor
- filename: File to save image to
- style: Visual style dictionary or style name
- interactive: Enable interactive features (matplotlib)
- plot_barriers: Whether to draw barrier instructions
- reverse_bits: Reverse bit order in display
- justify: Justification ('left', 'right', 'none')
- vertical_compression: Compression level ('high', 'medium', 'low')
- idle_wires: Display idle wires
- with_layout: Show physical layout information
- fold: Fold circuit at specified width
- ax: Matplotlib axes object
- initial_state: Display initial state
- cregbundle: Bundle classical registers
- wire_order: Custom wire ordering
- expr_len: Maximum expression length
Returns:
str or matplotlib.Figure: Circuit drawing
"""
def dag_drawer(dag, scale=0.7, filename=None, style='color'):
"""
Draw DAG circuit representation.
Parameters:
- dag: DAGCircuit to draw
- scale: Image scaling
- filename: Output filename
- style: Drawing style
Returns:
PIL.Image: DAG visualization
"""
def timeline_drawer(circuit, style=None, filename=None, show_idle=True,
show_barriers=True, show_delays=True, time_range=None,
time_unit='dt', disable_channels=None, show_snapshot_info=False,
plot_kwargs=None):
"""
Draw instruction timeline for scheduled circuits.
Parameters:
- circuit: Scheduled QuantumCircuit
- style: Timeline style
- filename: Output filename
- show_idle: Show idle periods
- show_barriers: Show barrier instructions
- show_delays: Show delay instructions
- time_range: Time range to display
- time_unit: Time unit for display
- disable_channels: Channels to hide
- show_snapshot_info: Show snapshot information
- plot_kwargs: Additional plotting arguments
Returns:
matplotlib.Figure: Timeline plot
"""Visualize quantum states in various representations.
def plot_bloch_vector(bloch, title='', ax=None, figsize=None, coord_type='cartesian'):
"""
Plot single qubit state on Bloch sphere.
Parameters:
- bloch: 3D vector [x, y, z] on Bloch sphere
- title: Plot title
- ax: Matplotlib axes
- figsize: Figure size
- coord_type: Coordinate type ('cartesian', 'spherical')
Returns:
matplotlib.Figure: Bloch sphere plot
"""
def plot_bloch_multivector(state, title='', figsize=None, reverse_bits=False):
"""
Plot multi-qubit state as multiple Bloch spheres.
Parameters:
- state: Quantum state (Statevector, DensityMatrix, or array)
- title: Plot title
- figsize: Figure size
- reverse_bits: Reverse qubit ordering
Returns:
matplotlib.Figure: Multi-Bloch sphere plot
"""
def plot_state_city(state, title='', figsize=None, color=None, alpha=1,
ax_real=None, ax_imag=None, ket=False):
"""
Plot quantum state in city (bar) format.
Parameters:
- state: Quantum state
- title: Plot title
- figsize: Figure size
- color: Bar colors
- alpha: Transparency
- ax_real: Axes for real part
- ax_imag: Axes for imaginary part
- ket: Use ket notation for labels
Returns:
matplotlib.Figure: City plot
"""
def plot_state_hinton(state, title='', figsize=None):
"""
Plot quantum state as Hinton diagram.
Parameters:
- state: Quantum state
- title: Plot title
- figsize: Figure size
Returns:
matplotlib.Figure: Hinton diagram
"""
def plot_state_paulivec(state, title='', figsize=None, color=None):
"""
Plot quantum state decomposition in Pauli basis.
Parameters:
- state: Quantum state
- title: Plot title
- figsize: Figure size
- color: Bar colors
Returns:
matplotlib.Figure: Pauli vector plot
"""
def plot_state_qsphere(state, figsize=None, ax=None, show_state_labels=False,
show_state_phases=False, use_degrees=False):
"""
Plot quantum state on Q-sphere.
Parameters:
- state: Quantum state
- figsize: Figure size
- ax: Matplotlib axes
- show_state_labels: Show state labels
- show_state_phases: Show phase information
- use_degrees: Use degrees for phases
Returns:
matplotlib.Figure: Q-sphere plot
"""
def state_drawer(state, output='text', **drawer_args):
"""
General quantum state visualization interface.
Parameters:
- state: Quantum state
- output: Output format ('text', 'latex', 'qsphere', 'hinton', 'bloch', 'city')
- **drawer_args: Additional arguments for specific drawers
Returns:
Visualization output (format-dependent)
"""Visualize measurement results and probability distributions.
def plot_histogram(data, figsize=(7, 5), color=None, number_to_keep=None,
sort='asc', target_string=None, legend=None, bar_labels=True,
title=None, ax=None, filename=None):
"""
Plot measurement result histogram.
Parameters:
- data: Counts dictionary or list of counts
- figsize: Figure size
- color: Bar colors
- number_to_keep: Number of top results to show
- sort: Sorting order ('asc', 'desc', 'hamming', 'value', 'value_desc')
- target_string: Highlight specific measurement outcome
- legend: Legend labels
- bar_labels: Show value labels on bars
- title: Plot title
- ax: Matplotlib axes
- filename: Save to file
Returns:
matplotlib.Figure: Histogram plot
"""
def plot_distribution(data, figsize=(7, 5), color=None, number_to_keep=None,
sort='asc', target_string=None, legend=None, bar_labels=True,
title=None, ax=None, filename=None):
"""
Plot probability distribution.
Parameters:
- data: Probability dictionary or list of probabilities
- Other parameters: Same as plot_histogram
Returns:
matplotlib.Figure: Distribution plot
"""Visualize quantum hardware topologies and properties.
def plot_gate_map(backend, figsize=None, plot_directed=False, label_qubits=True,
qubit_size=None, line_width=4, font_size=None, qubit_color=None,
qubit_labels=None, line_color=None, font_color='w', ax=None):
"""
Plot backend gate connectivity map.
Parameters:
- backend: Backend object
- figsize: Figure size
- plot_directed: Show directed edges
- label_qubits: Show qubit labels
- qubit_size: Size of qubit markers
- line_width: Connection line width
- font_size: Label font size
- qubit_color: Qubit marker colors
- qubit_labels: Custom qubit labels
- line_color: Connection line color
- font_color: Font color
- ax: Matplotlib axes
Returns:
matplotlib.Figure: Gate map plot
"""
def plot_error_map(backend, figsize=None, show_title=True, remove_badcal_edges=True):
"""
Plot backend error rate map.
Parameters:
- backend: Backend object with properties
- figsize: Figure size
- show_title: Show plot title
- remove_badcal_edges: Remove poorly calibrated edges
Returns:
matplotlib.Figure: Error map plot
"""
def plot_circuit_layout(circuit, backend, view='virtual', fold=None):
"""
Plot circuit layout on backend topology.
Parameters:
- circuit: Transpiled QuantumCircuit with layout
- backend: Target backend
- view: Layout view ('virtual', 'physical')
- fold: Fold long circuits
Returns:
matplotlib.Figure: Circuit layout visualization
"""
def plot_coupling_map(coupling_map, figsize=None, plot_directed=False,
label_qubits=True, qubit_size=None, line_width=4,
font_size=None, qubit_color=None, qubit_labels=None,
line_color=None, font_color='w', ax=None):
"""
Plot coupling map topology.
Parameters:
- coupling_map: CouplingMap object
- Other parameters: Same as plot_gate_map
Returns:
matplotlib.Figure: Coupling map plot
"""Visualize transpilation pass manager workflows.
def pass_manager_drawer(pass_manager, filename=None, style=None, raw=False):
"""
Draw pass manager execution flow.
Parameters:
- pass_manager: PassManager object
- filename: Output filename
- style: Drawing style
- raw: Return raw graph data
Returns:
matplotlib.Figure or graphviz.Digraph: Pass manager flow diagram
"""
def staged_pass_manager_drawer(staged_pass_manager, filename=None, style=None):
"""
Draw staged pass manager with multiple stages.
Parameters:
- staged_pass_manager: StagedPassManager object
- filename: Output filename
- style: Drawing style
Returns:
matplotlib.Figure: Staged pass manager diagram
"""Advanced visualization features for detailed analysis.
def visualize_transition(circuit, trace=False, saveas=None, fpg=100, spg=2):
"""
Visualize single-qubit gate transitions on Bloch sphere.
Parameters:
- circuit: Single-qubit QuantumCircuit
- trace: Show trace of state evolution
- saveas: Save animation to file
- fpg: Frames per gate
- spg: Seconds per gate
Returns:
matplotlib.animation.FuncAnimation: Bloch sphere animation
"""
def array_to_latex(array, precision=10, prefix="", source=False, max_size=8):
"""
Convert numpy array to LaTeX representation.
Parameters:
- array: Numpy array to convert
- precision: Decimal precision
- prefix: LaTeX prefix string
- source: Return LaTeX source code
- max_size: Maximum array size to display
Returns:
str: LaTeX representation
"""Style management for consistent visualization appearance.
class QiskitDrawStyle:
"""Style configuration for Qiskit visualizations."""
def __init__(self):
"""Initialize default style."""
def set_style(self, style_dict):
"""
Update style settings.
Parameters:
- style_dict: Dictionary of style parameters
"""
def get_style(self):
"""Get current style dictionary."""
# Predefined styles
STYLES = {
'default': {},
'bw': {}, # Black and white
'iqx': {}, # IBM Quantum Experience style
'textbook': {}, # Textbook style
}
def set_matplotlib_style(style_name):
"""
Set global matplotlib style for Qiskit plots.
Parameters:
- style_name: Style name from STYLES
"""from qiskit import QuantumCircuit
from qiskit.visualization import *
from qiskit.quantum_info import Statevector
import numpy as np
# Circuit visualization
circuit = QuantumCircuit(3, 3)
circuit.h(0)
circuit.cx(0, 1)
circuit.cx(1, 2)
circuit.measure_all()
# Draw circuit in different formats
print(circuit.draw()) # Text format
circuit.draw('mpl') # Matplotlib
circuit.draw('latex') # LaTeX
circuit.draw('mpl', filename='circuit.png') # Save to file
# State visualization
bell_state = Statevector.from_label('00')
bell_state = bell_state.evolve(circuit.remove_final_measurements())
# Multiple state representations
plot_bloch_multivector(bell_state) # Bloch spheres
plot_state_qsphere(bell_state) # Q-sphere
plot_state_city(bell_state) # City plot
plot_state_hinton(bell_state) # Hinton diagram
# Measurement result visualization
counts = {'00': 480, '11': 520}
plot_histogram(counts, title='Bell State Measurements')
# Multiple datasets comparison
counts_list = [
{'00': 480, '11': 520},
{'00': 510, '11': 490},
{'00': 495, '11': 505}
]
plot_histogram(counts_list, legend=['Run 1', 'Run 2', 'Run 3'])
# Hardware visualization
from qiskit.providers.fake_provider import FakeManila
backend = FakeManila()
plot_gate_map(backend) # Connectivity map
plot_error_map(backend) # Error rates
# Circuit layout on hardware
from qiskit import transpile
transpiled = transpile(circuit, backend)
plot_circuit_layout(transpiled, backend)
# Pass manager visualization
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import Optimize1qGates, CXCancellation
pm = PassManager()
pm.append(Optimize1qGates())
pm.append(CXCancellation())
pass_manager_drawer(pm)
# Animation of single-qubit evolution
single_qubit = QuantumCircuit(1)
single_qubit.h(0)
single_qubit.t(0)
single_qubit.h(0)
visualize_transition(single_qubit, trace=True)
# Custom styling
custom_style = {
'backgroundcolor': '#ffffff',
'edgecolor': '#000000',
'gatefacecolor': '#ffffff',
'gatetextcolor': '#000000',
'linecolor': '#000000',
'textcolor': '#000000'
}
circuit.draw('mpl', style=custom_style)
# LaTeX array conversion
state_vector = np.array([1/np.sqrt(2), 0, 0, 1/np.sqrt(2)])
latex_repr = array_to_latex(state_vector, precision=3)
print(latex_repr)Install with Tessl CLI
npx tessl i tessl/pypi-qiskit