ข้ามไปยังเนื้อหาหลัก

แสดงผลลัพธ์

เวอร์ชันแพ็กเกจ

โค้ดในหน้านี้พัฒนาโดยใช้ requirement ต่อไปนี้ แนะนำให้ใช้เวอร์ชันเหล่านี้หรือใหม่กว่า

qiskit[all]~=2.3.0
qiskit-ibm-runtime~=0.43.1

พล็อต histogram

ฟังก์ชัน plot_histogram แสดงผลลัพธ์จากการ sampling quantum circuit บน QPU

การใช้ output จากฟังก์ชัน

ฟังก์ชันนี้คืน object matplotlib.Figure เมื่อบรรทัดสุดท้ายของ code cell output เป็น object เหล่านี้ Jupyter notebook จะแสดงไว้ใต้ cell ถ้าเรียกใช้ฟังก์ชันเหล่านี้ในสภาพแวดล้อมอื่นหรือใน script คุณต้องแสดงหรือบันทึก output โดยตรง

มีสองตัวเลือก:

  • เรียก .show() บน object ที่คืนมาเพื่อเปิดรูปภาพในหน้าต่างใหม่ (สมมติว่า matplotlib backend ที่กำหนดค่าไว้เป็นแบบ interactive)
  • เรียก .savefig("out.png") เพื่อบันทึก figure ไปที่ out.png ใน working directory ปัจจุบัน เมธอด savefig() รับ path เพื่อให้ปรับตำแหน่งและชื่อไฟล์ได้ ตัวอย่างเช่น plot_state_city(psi).savefig("out.png")

ตัวอย่างเช่น สร้าง Bell state สองqubit:

# Added by doQumentation — required packages for this notebook
!pip install -q matplotlib numpy qiskit qiskit-ibm-runtime
from qiskit_ibm_runtime import QiskitRuntimeService, SamplerV2 as Sampler
from qiskit.transpiler import generate_preset_pass_manager

from qiskit.circuit import QuantumCircuit
from qiskit.visualization import plot_histogram

service = QiskitRuntimeService()

backend = service.least_busy(simulator=False, operational=True)
# Quantum circuit to make a Bell state
bell = QuantumCircuit(2)
bell.h(0)
bell.cx(0, 1)
bell.measure_all()

pm = generate_preset_pass_manager(backend=backend, optimization_level=1)
isa_circuit = pm.run(bell)

# execute the quantum circuit
sampler = Sampler(backend)
job = sampler.run([isa_circuit])
result = job.result()

print(result)
PrimitiveResult([SamplerPubResult(data=DataBin(meas=BitArray(<shape=(), num_shots=4096, num_bits=2>)), metadata={'circuit_metadata': {}})], metadata={'execution': {'execution_spans': ExecutionSpans([DoubleSliceSpan(<start='2026-01-15 07:11:30', stop='2026-01-15 07:11:32', size=4096>)])}, 'version': 2})
plot_histogram(result[0].data.meas.get_counts())

Output of the previous code cell

option เมื่อพล็อต histogram

ใช้ option ต่อไปนี้สำหรับ plot_histogram เพื่อปรับกราฟผลลัพธ์

  • legend: ให้ label สำหรับการรัน รับรายการ string ที่ใช้ label ผลลัพธ์ของแต่ละการรัน มีประโยชน์มากที่สุดเมื่อพล็อตผลลัพธ์หลายการรันใน histogram เดียวกัน
  • sort: ปรับลำดับของแท่งใน histogram สามารถตั้งเป็นลำดับจากน้อยไปมากด้วย asc หรือจากมากไปน้อยด้วย desc
  • number_to_keep: รับจำนวนเต็มสำหรับจำนวน term ที่จะแสดง ส่วนที่เหลือจะถูกรวมเป็นแท่งเดียวชื่อ "rest"
  • color: ปรับสีของแท่ง รับ string หรือรายการ string ของสีที่ใช้สำหรับแท่งในแต่ละการรัน
  • bar_labels: ปรับว่าจะพิมพ์ label เหนือแท่งหรือไม่
  • figsize: รับ tuple ของขนาดเป็นนิ้วสำหรับ figure ผลลัพธ์
# Execute two-qubit Bell state again
sampler.options.default_shots = 1000

job = sampler.run([isa_circuit])
second_result = job.result()

# Plot results with custom options
plot_histogram(
[
result[0].data.meas.get_counts(),
second_result[0].data.meas.get_counts(),
],
legend=["first", "second"],
sort="desc",
figsize=(15, 12),
color=["orange", "black"],
bar_labels=False,
)

Output of the previous code cell

พล็อตผลลัพธ์ Estimator

Qiskit ไม่มีฟังก์ชัน built-in สำหรับพล็อตผลลัพธ์ Estimator แต่สามารถใช้ bar plot ของ Matplotlib สำหรับการแสดงผลอย่างรวดเร็ว

เพื่อสาธิต cell ต่อไปนี้ประมาณค่า expectation value ของ observable เจ็ดตัวที่แตกต่างกันบน quantum state

import numpy as np
from qiskit import QuantumCircuit
from qiskit.quantum_info import SparsePauliOp
from qiskit_ibm_runtime import EstimatorV2 as Estimator
from qiskit.transpiler import generate_preset_pass_manager
from matplotlib import pyplot as plt

# Simple estimation experiment to create results
qc = QuantumCircuit(2)
qc.h(0)
qc.crx(1.5, 0, 1)

observables_labels = ["ZZ", "XX", "YZ", "ZY", "XY", "XZ", "ZX"]
observables = [SparsePauliOp(label) for label in observables_labels]

service = QiskitRuntimeService()

pm = generate_preset_pass_manager(backend=backend, optimization_level=1)
isa_circuit = pm.run(qc)
isa_observables = [
operator.apply_layout(isa_circuit.layout) for operator in observables
]

# Reshape observable array for broadcasting
reshaped_ops = np.fromiter(isa_observables, dtype=object)
reshaped_ops = reshaped_ops.reshape((7, 1))

estimator = Estimator(backend)
job = estimator.run([(isa_circuit, reshaped_ops)])
result = job.result()[0]
exp_val = job.result()[0].data.evs
print(result)

# Since the result array is structured as a 2D array where each element is a
# list containing a single value, you need to flatten the array.

# Plot using Matplotlib
plt.bar(observables_labels, exp_val.flatten())
PubResult(data=DataBin(evs=np.ndarray(<shape=(7, 1), dtype=float64>), stds=np.ndarray(<shape=(7, 1), dtype=float64>), ensemble_standard_error=np.ndarray(<shape=(7, 1), dtype=float64>), shape=(7, 1)), metadata={'shots': 4096, 'target_precision': 0.015625, 'circuit_metadata': {}, 'resilience': {}, 'num_randomizations': 32})
<BarContainer object of 7 artists>

Output of the previous code cell

cell ต่อไปนี้ใช้ standard error ที่ประมาณการของแต่ละผลลัพธ์และเพิ่มเป็น error bar ดู เอกสาร bar plot สำหรับคำอธิบายเต็มของพล็อต

standard_error = job.result()[0].data.stds

_, ax = plt.subplots()
ax.bar(
observables_labels,
exp_val.flatten(),
yerr=standard_error.flatten(),
capsize=2,
)
ax.set_title("Expectation values (with standard errors)")
Text(0.5, 1.0, 'Expectation values (with standard errors)')

Output of the previous code cell

Source: IBM Quantum docs — updated 1 เม.ย. 2569
English version on doQumentation — updated 7 พ.ค. 2569
This translation based on the English version of 11 มี.ค. 2569