You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyCharm运行Qiskit代码无法显示plot_histogram直方图问题咨询

问题场景

在PyCharm环境中使用Qiskit开发量子程序时,可正常获取并打印量子电路运行的计数结果,但无法展示plot_histogram方法生成的结果直方图。
复现问题的完整代码如下:

import numpy as np
from qiskit import QuantumCircuit, transpile
from qiskit.providers.aer import QasmSimulator
from qiskit.visualization import plot_histogram
from matplotlib import pyplot as plt

simulator = QasmSimulator()
circuit = QuantumCircuit(2, 2)
circuit.h(0)

# Add a CX (CNOT) gate on control qubit 0 and target qubit 1
circuit.cx(0, 1)

# Map the quantum measurement to the classical bits
circuit.measure([0,1], [0,1])
compiled_circuit = transpile(circuit, simulator)
job = simulator.run(compiled_circuit, shots=1000)
result = job.result()
counts = result.get_counts(compiled_circuit)
print("\nTotal count for 00 and 11 are:",counts)
plot_histogram(counts)

代码正常运行后预期展示的直方图效果如下:
预期直方图效果

问题原因

plot_histogram是基于Matplotlib封装的可视化方法,调用后只会完成直方图对象的构造渲染,不会主动触发Matplotlib的绘图展示逻辑。Jupyter Notebook这类交互式运行环境会自动捕获并渲染Matplotlib对象,但PyCharm的常规Python运行模式没有自动渲染机制,因此不会弹出绘图窗口。

解决方法

可根据使用习惯选择以下任意一种方案:

  • 方案1:补充Matplotlib展示触发代码
    在plot_histogram(counts)代码行后新增plt.show(),主动唤起Matplotlib绘图窗口即可看到直方图,修改后的代码末尾段如下:
    print("\nTotal count for 00 and 11 are:",counts)
    plot_histogram(counts)
    plt.show() # 新增该行触发窗口展示
    
  • 方案2:开启PyCharm内置科学绘图窗口
    打开PyCharm设置页,依次进入Settings | Tools | Python Scientific,勾选Show plots in tool window选项,保存设置后再次运行代码,直方图会直接展示在PyCharm内置的工具窗口中,无需额外添加plt.show()。

内容的提问来源于stack exchange,提问作者82Hrh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 17:03:21