or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

circuit-construction.mdcircuit-formats.mdgates-operations.mdindex.mdprimitives.mdproviders.mdquantum-information.mdsynthesis.mdtranspilation.mdvisualization.md

visualization.mddocs/

0

# Visualization

1

2

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.

3

4

## Capabilities

5

6

### Circuit Visualization

7

8

Draw quantum circuits in multiple formats for analysis and presentation.

9

10

```python { .api }

11

def circuit_drawer(circuit, output=None, scale=None, filename=None, style=None,

12

interactive=False, plot_barriers=True, reverse_bits=None,

13

justify=None, vertical_compression='medium', idle_wires=True,

14

with_layout=True, fold=None, ax=None, initial_state=False,

15

cregbundle=None, wire_order=None, expr_len=30):

16

"""

17

Draw quantum circuit.

18

19

Parameters:

20

- circuit: QuantumCircuit to draw

21

- output: Output format ('text', 'mpl', 'latex', 'latex_source')

22

- scale: Image scaling factor

23

- filename: File to save image to

24

- style: Visual style dictionary or style name

25

- interactive: Enable interactive features (matplotlib)

26

- plot_barriers: Whether to draw barrier instructions

27

- reverse_bits: Reverse bit order in display

28

- justify: Justification ('left', 'right', 'none')

29

- vertical_compression: Compression level ('high', 'medium', 'low')

30

- idle_wires: Display idle wires

31

- with_layout: Show physical layout information

32

- fold: Fold circuit at specified width

33

- ax: Matplotlib axes object

34

- initial_state: Display initial state

35

- cregbundle: Bundle classical registers

36

- wire_order: Custom wire ordering

37

- expr_len: Maximum expression length

38

39

Returns:

40

str or matplotlib.Figure: Circuit drawing

41

"""

42

43

def dag_drawer(dag, scale=0.7, filename=None, style='color'):

44

"""

45

Draw DAG circuit representation.

46

47

Parameters:

48

- dag: DAGCircuit to draw

49

- scale: Image scaling

50

- filename: Output filename

51

- style: Drawing style

52

53

Returns:

54

PIL.Image: DAG visualization

55

"""

56

57

def timeline_drawer(circuit, style=None, filename=None, show_idle=True,

58

show_barriers=True, show_delays=True, time_range=None,

59

time_unit='dt', disable_channels=None, show_snapshot_info=False,

60

plot_kwargs=None):

61

"""

62

Draw instruction timeline for scheduled circuits.

63

64

Parameters:

65

- circuit: Scheduled QuantumCircuit

66

- style: Timeline style

67

- filename: Output filename

68

- show_idle: Show idle periods

69

- show_barriers: Show barrier instructions

70

- show_delays: Show delay instructions

71

- time_range: Time range to display

72

- time_unit: Time unit for display

73

- disable_channels: Channels to hide

74

- show_snapshot_info: Show snapshot information

75

- plot_kwargs: Additional plotting arguments

76

77

Returns:

78

matplotlib.Figure: Timeline plot

79

"""

80

```

81

82

### State Visualization

83

84

Visualize quantum states in various representations.

85

86

```python { .api }

87

def plot_bloch_vector(bloch, title='', ax=None, figsize=None, coord_type='cartesian'):

88

"""

89

Plot single qubit state on Bloch sphere.

90

91

Parameters:

92

- bloch: 3D vector [x, y, z] on Bloch sphere

93

- title: Plot title

94

- ax: Matplotlib axes

95

- figsize: Figure size

96

- coord_type: Coordinate type ('cartesian', 'spherical')

97

98

Returns:

99

matplotlib.Figure: Bloch sphere plot

100

"""

101

102

def plot_bloch_multivector(state, title='', figsize=None, reverse_bits=False):

103

"""

104

Plot multi-qubit state as multiple Bloch spheres.

105

106

Parameters:

107

- state: Quantum state (Statevector, DensityMatrix, or array)

108

- title: Plot title

109

- figsize: Figure size

110

- reverse_bits: Reverse qubit ordering

111

112

Returns:

113

matplotlib.Figure: Multi-Bloch sphere plot

114

"""

115

116

def plot_state_city(state, title='', figsize=None, color=None, alpha=1,

117

ax_real=None, ax_imag=None, ket=False):

118

"""

119

Plot quantum state in city (bar) format.

120

121

Parameters:

122

- state: Quantum state

123

- title: Plot title

124

- figsize: Figure size

125

- color: Bar colors

126

- alpha: Transparency

127

- ax_real: Axes for real part

128

- ax_imag: Axes for imaginary part

129

- ket: Use ket notation for labels

130

131

Returns:

132

matplotlib.Figure: City plot

133

"""

134

135

def plot_state_hinton(state, title='', figsize=None):

136

"""

137

Plot quantum state as Hinton diagram.

138

139

Parameters:

140

- state: Quantum state

141

- title: Plot title

142

- figsize: Figure size

143

144

Returns:

145

matplotlib.Figure: Hinton diagram

146

"""

147

148

def plot_state_paulivec(state, title='', figsize=None, color=None):

149

"""

150

Plot quantum state decomposition in Pauli basis.

151

152

Parameters:

153

- state: Quantum state

154

- title: Plot title

155

- figsize: Figure size

156

- color: Bar colors

157

158

Returns:

159

matplotlib.Figure: Pauli vector plot

160

"""

161

162

def plot_state_qsphere(state, figsize=None, ax=None, show_state_labels=False,

163

show_state_phases=False, use_degrees=False):

164

"""

165

Plot quantum state on Q-sphere.

166

167

Parameters:

168

- state: Quantum state

169

- figsize: Figure size

170

- ax: Matplotlib axes

171

- show_state_labels: Show state labels

172

- show_state_phases: Show phase information

173

- use_degrees: Use degrees for phases

174

175

Returns:

176

matplotlib.Figure: Q-sphere plot

177

"""

178

179

def state_drawer(state, output='text', **drawer_args):

180

"""

181

General quantum state visualization interface.

182

183

Parameters:

184

- state: Quantum state

185

- output: Output format ('text', 'latex', 'qsphere', 'hinton', 'bloch', 'city')

186

- **drawer_args: Additional arguments for specific drawers

187

188

Returns:

189

Visualization output (format-dependent)

190

"""

191

```

192

193

### Measurement and Distribution Visualization

194

195

Visualize measurement results and probability distributions.

196

197

```python { .api }

198

def plot_histogram(data, figsize=(7, 5), color=None, number_to_keep=None,

199

sort='asc', target_string=None, legend=None, bar_labels=True,

200

title=None, ax=None, filename=None):

201

"""

202

Plot measurement result histogram.

203

204

Parameters:

205

- data: Counts dictionary or list of counts

206

- figsize: Figure size

207

- color: Bar colors

208

- number_to_keep: Number of top results to show

209

- sort: Sorting order ('asc', 'desc', 'hamming', 'value', 'value_desc')

210

- target_string: Highlight specific measurement outcome

211

- legend: Legend labels

212

- bar_labels: Show value labels on bars

213

- title: Plot title

214

- ax: Matplotlib axes

215

- filename: Save to file

216

217

Returns:

218

matplotlib.Figure: Histogram plot

219

"""

220

221

def plot_distribution(data, figsize=(7, 5), color=None, number_to_keep=None,

222

sort='asc', target_string=None, legend=None, bar_labels=True,

223

title=None, ax=None, filename=None):

224

"""

225

Plot probability distribution.

226

227

Parameters:

228

- data: Probability dictionary or list of probabilities

229

- Other parameters: Same as plot_histogram

230

231

Returns:

232

matplotlib.Figure: Distribution plot

233

"""

234

```

235

236

### Device and Hardware Visualization

237

238

Visualize quantum hardware topologies and properties.

239

240

```python { .api }

241

def plot_gate_map(backend, figsize=None, plot_directed=False, label_qubits=True,

242

qubit_size=None, line_width=4, font_size=None, qubit_color=None,

243

qubit_labels=None, line_color=None, font_color='w', ax=None):

244

"""

245

Plot backend gate connectivity map.

246

247

Parameters:

248

- backend: Backend object

249

- figsize: Figure size

250

- plot_directed: Show directed edges

251

- label_qubits: Show qubit labels

252

- qubit_size: Size of qubit markers

253

- line_width: Connection line width

254

- font_size: Label font size

255

- qubit_color: Qubit marker colors

256

- qubit_labels: Custom qubit labels

257

- line_color: Connection line color

258

- font_color: Font color

259

- ax: Matplotlib axes

260

261

Returns:

262

matplotlib.Figure: Gate map plot

263

"""

264

265

def plot_error_map(backend, figsize=None, show_title=True, remove_badcal_edges=True):

266

"""

267

Plot backend error rate map.

268

269

Parameters:

270

- backend: Backend object with properties

271

- figsize: Figure size

272

- show_title: Show plot title

273

- remove_badcal_edges: Remove poorly calibrated edges

274

275

Returns:

276

matplotlib.Figure: Error map plot

277

"""

278

279

def plot_circuit_layout(circuit, backend, view='virtual', fold=None):

280

"""

281

Plot circuit layout on backend topology.

282

283

Parameters:

284

- circuit: Transpiled QuantumCircuit with layout

285

- backend: Target backend

286

- view: Layout view ('virtual', 'physical')

287

- fold: Fold long circuits

288

289

Returns:

290

matplotlib.Figure: Circuit layout visualization

291

"""

292

293

def plot_coupling_map(coupling_map, figsize=None, plot_directed=False,

294

label_qubits=True, qubit_size=None, line_width=4,

295

font_size=None, qubit_color=None, qubit_labels=None,

296

line_color=None, font_color='w', ax=None):

297

"""

298

Plot coupling map topology.

299

300

Parameters:

301

- coupling_map: CouplingMap object

302

- Other parameters: Same as plot_gate_map

303

304

Returns:

305

matplotlib.Figure: Coupling map plot

306

"""

307

```

308

309

### Pass Manager Visualization

310

311

Visualize transpilation pass manager workflows.

312

313

```python { .api }

314

def pass_manager_drawer(pass_manager, filename=None, style=None, raw=False):

315

"""

316

Draw pass manager execution flow.

317

318

Parameters:

319

- pass_manager: PassManager object

320

- filename: Output filename

321

- style: Drawing style

322

- raw: Return raw graph data

323

324

Returns:

325

matplotlib.Figure or graphviz.Digraph: Pass manager flow diagram

326

"""

327

328

def staged_pass_manager_drawer(staged_pass_manager, filename=None, style=None):

329

"""

330

Draw staged pass manager with multiple stages.

331

332

Parameters:

333

- staged_pass_manager: StagedPassManager object

334

- filename: Output filename

335

- style: Drawing style

336

337

Returns:

338

matplotlib.Figure: Staged pass manager diagram

339

"""

340

```

341

342

### Interactive and Advanced Visualization

343

344

Advanced visualization features for detailed analysis.

345

346

```python { .api }

347

def visualize_transition(circuit, trace=False, saveas=None, fpg=100, spg=2):

348

"""

349

Visualize single-qubit gate transitions on Bloch sphere.

350

351

Parameters:

352

- circuit: Single-qubit QuantumCircuit

353

- trace: Show trace of state evolution

354

- saveas: Save animation to file

355

- fpg: Frames per gate

356

- spg: Seconds per gate

357

358

Returns:

359

matplotlib.animation.FuncAnimation: Bloch sphere animation

360

"""

361

362

def array_to_latex(array, precision=10, prefix="", source=False, max_size=8):

363

"""

364

Convert numpy array to LaTeX representation.

365

366

Parameters:

367

- array: Numpy array to convert

368

- precision: Decimal precision

369

- prefix: LaTeX prefix string

370

- source: Return LaTeX source code

371

- max_size: Maximum array size to display

372

373

Returns:

374

str: LaTeX representation

375

"""

376

```

377

378

### Visualization Styling and Customization

379

380

Style management for consistent visualization appearance.

381

382

```python { .api }

383

class QiskitDrawStyle:

384

"""Style configuration for Qiskit visualizations."""

385

386

def __init__(self):

387

"""Initialize default style."""

388

389

def set_style(self, style_dict):

390

"""

391

Update style settings.

392

393

Parameters:

394

- style_dict: Dictionary of style parameters

395

"""

396

397

def get_style(self):

398

"""Get current style dictionary."""

399

400

# Predefined styles

401

STYLES = {

402

'default': {},

403

'bw': {}, # Black and white

404

'iqx': {}, # IBM Quantum Experience style

405

'textbook': {}, # Textbook style

406

}

407

408

def set_matplotlib_style(style_name):

409

"""

410

Set global matplotlib style for Qiskit plots.

411

412

Parameters:

413

- style_name: Style name from STYLES

414

"""

415

```

416

417

### Usage Examples

418

419

```python

420

from qiskit import QuantumCircuit

421

from qiskit.visualization import *

422

from qiskit.quantum_info import Statevector

423

import numpy as np

424

425

# Circuit visualization

426

circuit = QuantumCircuit(3, 3)

427

circuit.h(0)

428

circuit.cx(0, 1)

429

circuit.cx(1, 2)

430

circuit.measure_all()

431

432

# Draw circuit in different formats

433

print(circuit.draw()) # Text format

434

circuit.draw('mpl') # Matplotlib

435

circuit.draw('latex') # LaTeX

436

circuit.draw('mpl', filename='circuit.png') # Save to file

437

438

# State visualization

439

bell_state = Statevector.from_label('00')

440

bell_state = bell_state.evolve(circuit.remove_final_measurements())

441

442

# Multiple state representations

443

plot_bloch_multivector(bell_state) # Bloch spheres

444

plot_state_qsphere(bell_state) # Q-sphere

445

plot_state_city(bell_state) # City plot

446

plot_state_hinton(bell_state) # Hinton diagram

447

448

# Measurement result visualization

449

counts = {'00': 480, '11': 520}

450

plot_histogram(counts, title='Bell State Measurements')

451

452

# Multiple datasets comparison

453

counts_list = [

454

{'00': 480, '11': 520},

455

{'00': 510, '11': 490},

456

{'00': 495, '11': 505}

457

]

458

plot_histogram(counts_list, legend=['Run 1', 'Run 2', 'Run 3'])

459

460

# Hardware visualization

461

from qiskit.providers.fake_provider import FakeManila

462

backend = FakeManila()

463

464

plot_gate_map(backend) # Connectivity map

465

plot_error_map(backend) # Error rates

466

467

# Circuit layout on hardware

468

from qiskit import transpile

469

transpiled = transpile(circuit, backend)

470

plot_circuit_layout(transpiled, backend)

471

472

# Pass manager visualization

473

from qiskit.transpiler import PassManager

474

from qiskit.transpiler.passes import Optimize1qGates, CXCancellation

475

476

pm = PassManager()

477

pm.append(Optimize1qGates())

478

pm.append(CXCancellation())

479

pass_manager_drawer(pm)

480

481

# Animation of single-qubit evolution

482

single_qubit = QuantumCircuit(1)

483

single_qubit.h(0)

484

single_qubit.t(0)

485

single_qubit.h(0)

486

487

visualize_transition(single_qubit, trace=True)

488

489

# Custom styling

490

custom_style = {

491

'backgroundcolor': '#ffffff',

492

'edgecolor': '#000000',

493

'gatefacecolor': '#ffffff',

494

'gatetextcolor': '#000000',

495

'linecolor': '#000000',

496

'textcolor': '#000000'

497

}

498

499

circuit.draw('mpl', style=custom_style)

500

501

# LaTeX array conversion

502

state_vector = np.array([1/np.sqrt(2), 0, 0, 1/np.sqrt(2)])

503

latex_repr = array_to_latex(state_vector, precision=3)

504

print(latex_repr)

505

```