[ PROMPT_NODE_27216 ]
Qiskit 可视化
[ SKILL_DOCUMENTATION ]
# Qiskit 可视化
Qiskit 为量子电路、测量结果和量子态提供了全面的可视化工具。
## 安装
安装可视化依赖:
bash
uv pip install "qiskit[visualization]" matplotlib
## 电路可视化
### 文本绘图
python
from qiskit import QuantumCircuit
qc = QuantumCircuit(3)
qc.h(0)
qc.cx(0, 1)
qc.cx(1, 2)
# 简单文本输出
print(qc.draw())
# 带有更多细节的文本
print(qc.draw('text', fold=-1)) # 不折叠长电路
### Matplotlib 绘图
python
# 高质量 matplotlib 图形
qc.draw('mpl')
# 保存到文件
fig = qc.draw('mpl')
fig.savefig('circuit.png', dpi=300, bbox_inches='tight')
### LaTeX 绘图
python
# 生成 LaTeX 电路图
qc.draw('latex')
# 保存 LaTeX 源码
latex_source = qc.draw('latex_source')
with open('circuit.tex', 'w') as f:
f.write(latex_source)
## 自定义电路绘图
### 样式选项
python
from qiskit.visualization import circuit_drawer
# 反转量子比特顺序
qc.draw('mpl', reverse_bits=True)
# 折叠长电路
qc.draw('mpl', fold=20) # 在20列处折叠
# 显示空闲导线
qc.draw('mpl', idle_wires=False)
# 添加初始状态
qc.draw('mpl', initial_state=True)
### 颜色自定义
python
style = {
'displaycolor': {
'h': ('#FA74A6', '#000000'), # Hadamard: 粉色
'cx': ('#A8D0DB', '#000000'), # CNOT: 浅蓝色
'measure': ('#F7E7B4', '#000000') # Measure: 黄色
}
}
qc.draw('mpl', style=style)
## 结果可视化
### 计数直方图
python
from qiskit.visualization import plot_histogram
from qiskit.primitives import StatevectorSampler
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
sampler = StatevectorSampler()
result = sampler.run([qc], shots=1024).result()
counts = result[0].data.meas.get_counts()
# 绘制直方图
plot_histogram(counts)
# 比较多个实验
counts1 = {'00': 500, '11': 524}
counts2 = {'00': 480, '11': 544}
plot_histogram([counts1, counts2], legend=['运行 1', '运行 2'])
# 保存图形
fig = plot_histogram(counts)
fig.savefig('histogram.png', dpi=300, bbox_inches='tight')
### 直方图选项
python
# 自定义颜色
plot_histogram(counts, color=['#1f77b4', '#ff7f0e'])
# 按值排序
plot_histogram(counts, sort='value')
# 设置柱状标签
plot_histogram(counts, bar_labels=True)
# 设置目标分布(用于比较)
target = {'00': 0.5, '11': 0.5}