pythonjupyter-notebookgoogle-colaboratoryquantum-computingqiskit

Quantum Circuit not drawing on Colab


So, I tried to simulate this gate on Colab using matplotlib. The histogram is showing at the end, but not the circuit. I have tried out all fixes suggested by ChatGPT such as force inline and circuit_drawer, but it did not work. Please help me with the solution.

qc_h = QuantumCircuit(1, 1, name = "qc")
qc_h.h(0)
qc_h.measure(0, 0)

qc_h.draw('mpl')

simulator_h = Aer.get_backend('qasm_simulator')
transpiled_circuit_h = transpile(qc_h, simulator_h)
job_h = simulator_h.run(transpiled_circuit_h, shots = 1024)
result_h = job_h.result()
counts_h = result_h.get_counts(qc_h)

plot_histogram(counts_h)

Solution

  • We have to define the matplotlib axes (e.g. two matplotlib subplots) and input the axis as a kwargument for draw and plot_histogram.

    from qiskit import QuantumCircuit
    from qiskit_aer import Aer
    from qiskit.compiler import transpile
    from qiskit.visualization import plot_histogram
    from matplotlib import pyplot as plt
    
    
    fig = plt.figure(figsize=(10, 10))
    ax = plt.subplot(1, 2, 1)
    qc_h = QuantumCircuit(1, 1, name='qc')
    qc_h.h(0)
    qc_h.measure(0, 0)
    qc_h.draw('mpl', ax=ax)
    
    ax = plt.subplot(1, 2, 2)
    simulator_h = Aer.get_backend('qasm_simulator')
    transpiled_circuit_h = transpile(qc_h, simulator_h)
    job_h = simulator_h.run(transpiled_circuit_h, shots=1024)
    result_h = job_h.result()
    counts_h = result_h.get_counts(qc_h)
    
    plot_histogram(counts_h, ax=ax)
    plt.show()
    

    Outputs:

    enter image description here

    Google Colab pips:

    !pip install qiskit
    !pip install pylatexenc
    !pip install qiskit_aer