Repository: Qiskit/qiskit

Issue:
mpl circ drawer fails with `idle_wires=False`
### Environment

- **Qiskit Terra version**: latest
- **Python version**: 
- **Operating system**: 


### What is happening?

```python

qc = QuantumCircuit(6, 5)
qc.x(5)
qc.h(range(6))
qc.cx(range(5),5)
qc.h(range(5))
qc.measure(range(5), range(5))

backend = provider.get_backend('ibm_geneva')
trans_qc = transpile(qc, backend, optimization_level=3, approximation_degree=0)
trans_qc.draw('mpl', idle_wires=False)
```

gives

Traceback (most recent call last):
  Input In [9] in <cell line: 2>
    trans_qc.draw('mpl', idle_wires=False)
  File /opt/miniconda3/envs/qiskit/lib/python3.10/site-packages/qiskit/circuit/quantumcircuit.py:1907 in draw
    return circuit_drawer(
  File /opt/miniconda3/envs/qiskit/lib/python3.10/site-packages/qiskit/visualization/circuit_visualization.py:231 in circuit_drawer
    image = _matplotlib_circuit_drawer(
  File /opt/miniconda3/envs/qiskit/lib/python3.10/site-packages/qiskit/visualization/circuit_visualization.py:601 in _matplotlib_circuit_drawer
    return qcd.draw(filename)
  File /opt/miniconda3/envs/qiskit/lib/python3.10/site-packages/qiskit/visualization/matplotlib.py:323 in draw
    max_anc = self._get_coords(n_lines)
  File /opt/miniconda3/envs/qiskit/lib/python3.10/site-packages/qiskit/visualization/matplotlib.py:579 in _get_coords
    q_indxs.append(self._wire_map[qarg])
KeyError: Qubit(QuantumRegister(27, 'q'), 0)

### How can we reproduce the issue?

Do above

### What should happen?

should not fail

### Any suggestions?

_No response_


Discussion:
A self-contained reproducer for assisting debugging:

```python
from qiskit import QuantumCircuit, transpile
from qiskit.providers.fake_provider import FakeKolkata

qc = QuantumCircuit(6, 5)
qc.x(5)
qc.h(range(6))
qc.cx(range(5),5)
qc.h(range(5))
qc.measure(range(5), range(5))

trans_qc = transpile(qc, FakeKolkata(), optimization_level=3, approximation_degree=0)
trans_qc.draw('mpl', idle_wires=False)
```

Resolving patch:
diff --git a/qiskit/visualization/latex.py b/qiskit/visualization/latex.py
--- a/qiskit/visualization/latex.py
+++ b/qiskit/visualization/latex.py
@@ -420,7 +420,7 @@ def _build_latex_array(self):
             for node in layer:
                 op = node.op
                 num_cols_op = 1
-                wire_list = [self._wire_map[qarg] for qarg in node.qargs]
+                wire_list = [self._wire_map[qarg] for qarg in node.qargs if qarg in self._qubits]
                 if op.condition:
                     self._add_condition(op, wire_list, column)
 
@@ -435,7 +435,9 @@ def _build_latex_array(self):
                     gate_text += get_param_str(op, "latex", ndigits=4)
                     gate_text = generate_latex_label(gate_text)
                     if node.cargs:
-                        cwire_list = [self._wire_map[carg] for carg in node.cargs]
+                        cwire_list = [
+                            self._wire_map[carg] for carg in node.cargs if carg in self._clbits
+                        ]
                     else:
                         cwire_list = []
 
@@ -582,7 +584,7 @@ def _build_measure(self, node, col):
     def _build_barrier(self, node, col):
         """Build a partial or full barrier if plot_barriers set"""
         if self._plot_barriers:
-            indexes = [self._wire_map[qarg] for qarg in node.qargs]
+            indexes = [self._wire_map[qarg] for qarg in node.qargs if qarg in self._qubits]
             indexes.sort()
             first = last = indexes[0]
             for index in indexes[1:]:
diff --git a/qiskit/visualization/matplotlib.py b/qiskit/visualization/matplotlib.py
--- a/qiskit/visualization/matplotlib.py
+++ b/qiskit/visualization/matplotlib.py
@@ -574,15 +574,17 @@ def _get_coords(self, n_lines):
                 # get qubit index
                 q_indxs = []
                 for qarg in node.qargs:
-                    q_indxs.append(self._wire_map[qarg])
+                    if qarg in self._qubits:
+                        q_indxs.append(self._wire_map[qarg])
 
                 c_indxs = []
                 for carg in node.cargs:
-                    register = get_bit_register(self._circuit, carg)
-                    if register is not None and self._cregbundle:
-                        c_indxs.append(self._wire_map[register])
-                    else:
-                        c_indxs.append(self._wire_map[carg])
+                    if carg in self._clbits:
+                        register = get_bit_register(self._circuit, carg)
+                        if register is not None and self._cregbundle:
+                            c_indxs.append(self._wire_map[register])
+                        else:
+                            c_indxs.append(self._wire_map[carg])
 
                 # qubit coordinate
                 self._data[node]["q_xy"] = [


Test patch:
diff --git a/test/ipynb/mpl/circuit/references/idle_wires_barrier.png b/test/ipynb/mpl/circuit/references/idle_wires_barrier.png
new file mode 100644
Binary files /dev/null and b/test/ipynb/mpl/circuit/references/idle_wires_barrier.png differ
diff --git a/test/ipynb/mpl/circuit/test_circuit_matplotlib_drawer.py b/test/ipynb/mpl/circuit/test_circuit_matplotlib_drawer.py
--- a/test/ipynb/mpl/circuit/test_circuit_matplotlib_drawer.py
+++ b/test/ipynb/mpl/circuit/test_circuit_matplotlib_drawer.py
@@ -896,6 +896,13 @@ def test_fold_with_conditions(self):
         circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 31)
         self.circuit_drawer(circuit, cregbundle=False, filename="fold_with_conditions.png")
 
+    def test_idle_wires_barrier(self):
+        """Test that idle_wires False works with barrier"""
+        circuit = QuantumCircuit(4, 4)
+        circuit.x(2)
+        circuit.barrier()
+        self.circuit_drawer(circuit, cregbundle=False, filename="idle_wires_barrier.png")
+
     def test_wire_order(self):
         """Test the wire_order option"""
         qr = QuantumRegister(4, "q")
diff --git a/test/python/visualization/references/test_latex_idle_wires_barrier.tex b/test/python/visualization/references/test_latex_idle_wires_barrier.tex
new file mode 100644
--- /dev/null
+++ b/test/python/visualization/references/test_latex_idle_wires_barrier.tex
@@ -0,0 +1,11 @@
+\documentclass[border=2px]{standalone}
+
+\usepackage[braket, qm]{qcircuit}
+\usepackage{graphicx}
+
+\begin{document}
+\scalebox{1.0}{
+\Qcircuit @C=1.0em @R=0.2em @!R { \\
+	 	\nghost{{q}_{2} :  } & \lstick{{q}_{2} :  } & \gate{\mathrm{X}} \barrier[0em]{0} & \qw & \qw & \qw\\
+\\ }}
+\end{document}
\ No newline at end of file
diff --git a/test/python/visualization/test_circuit_latex.py b/test/python/visualization/test_circuit_latex.py
--- a/test/python/visualization/test_circuit_latex.py
+++ b/test/python/visualization/test_circuit_latex.py
@@ -655,6 +655,15 @@ def test_sidetext_with_condition(self):
         circuit_drawer(circuit, cregbundle=False, filename=filename, output="latex_source")
         self.assertEqualToReference(filename)
 
+    def test_idle_wires_barrier(self):
+        """Test that idle_wires False works with barrier"""
+        filename = self._get_resource_path("test_latex_idle_wires_barrier.tex")
+        circuit = QuantumCircuit(4, 4)
+        circuit.x(2)
+        circuit.barrier()
+        circuit_drawer(circuit, idle_wires=False, filename=filename, output="latex_source")
+        self.assertEqualToReference(filename)
+
     def test_wire_order(self):
         """Test the wire_order option"""
         filename = self._get_resource_path("test_latex_wire_order.tex")