如何在PyCharm中正常显示Qiskit生成的可视化图表
问题原因
PyCharm社区版的默认Python运行环境/控制台不会自动渲染matplotlib绘图对象,Qiskit的plot_histogram()接口底层基于matplotlib实现,仅调用该函数没有触发显示逻辑时,控制台只会输出Figure对象的文本描述信息。
解决方法
- 方法1:显式调用matplotlib的显示接口(最通用,脚本运行/控制台运行都适用)
在代码开头补充导入matplotlib.pyplot,再在plot_histogram(counts)后添加plt.show()即可,修改后的完整代码如下:
from qiskit import * from qiskit.visualization import plot_histogram from qiskit.tools.monitor import job_monitor import matplotlib.pyplot as plt # 构造贝尔态量子电路 bell = QuantumCircuit(2 ,2) bell.h(0) bell.cx(0, 1) meas = QuantumCircuit(2, 2) meas.measure([0,1], [0,1]) # 执行量子电路 backend = BasicAer.get_backend('qasm_simulator') # 运行用的后端设备 circ = bell.compose(meas) result = backend.run(transpile(circ, backend), shots=1000).result() counts = result.get_counts(circ) print(counts) plot_histogram(counts) plt.show()
- 方法2:调整PyCharm控制台配置(适合偏好交互式运行的场景)
打开PyCharm的「File > Settings > Build, Execution, Deployment > Console > Python Console」,勾选「Run with Python Console」同时启用IPython支持,之后在控制台中运行代码时,调用plot_histogram(counts)后会自动在SciView窗口渲染图片,无需额外加plt.show()。
内容的提问来源于stack exchange,提问作者that_one_dude
相关产品推荐
相关产品推荐

