One of RDKit's most powerful features is its ability to generate high-quality 2D depictions of molecules directly in a Google Colab notebook.
When a molecule object is created with Chem.MolFromSmiles() is the last line in a code cell; the notebook automatically renders its 2D structure. This is the simplest way to visualize a molecule.
Drawing Molecules with Atom Numbering
For analysis, it's often helpful to see the index number of each atom in the structure. While RDKit doesn't have a single command for this, we can easily add atom numbers by iterating through the atoms and setting a specific property (molAtomMapNumber) before drawing. Let's look at the following examples.
Isobutanol with a SMILES "CC(C)CO" (Figure 1).
Code:
# Isobutanol
# Labeling atoms from 1 instead of 0 using RDKit
mol = Chem.MolFromSmiles("CC(C)CO")
# Label each atom starting from 1
for atom in mol.GetAtoms():
atom.SetAtomMapNum(atom.GetIdx() + 1)
# Visualize the molecule with atom numbers
Draw.MolToImage(mol, size=(300, 300))
Figure 1: Structure of Isobutanol.
2. Benzene with a SMILES "c1ccccc1" (Figure 2).
Code:
benzene = Chem.MolFromSmiles("c1ccccc1")
# Label each atom starting from 1
for atom in benzene.GetAtoms():
atom.SetAtomMapNum(atom.GetIdx() + 1)
# Visualize the molecule with atom numbers
Draw.MolToImage(benzene, size=(300, 300))
Figure 2: Structure of Benzene
3. Butane with a SMILES "CCCC" (Figure 3).
Code:
butane = Chem.MolFromSmiles("CCCC")
# Label each atom starting from 1
for atom in butane.GetAtoms():
atom.SetAtomMapNum(atom.GetIdx() + 1)
# Visualize the molecule with atom numbers
Draw.MolToImage(butane, size=(300, 300))
Figure 3: Structure of Butane
4. Aspirin with a SMILES "CC(=O)OC1=CC=CC=C1C(=O)O" (Figure 4).
Code:
# Labeling atoms from 1 instead of 0 using RDKit
aspirin = Chem.MolFromSmiles("CC(=O)OC1=CC=CC=C1C(=O)O")
# Label each atom starting from 1
for atom in aspirin.GetAtoms():
atom.SetAtomMapNum(atom.GetIdx() + 1)
# Visualize the molecule with atom numbers
Draw.MolToImage(aspirin, size=(300, 300))
Figure 4: Structure of Aspirin
5. Hexene with a SMILES "C=CCCCC" (Figure 5).
Code:
# Labeling atoms from 1 instead of 0 using RDKit
hexene = Chem.MolFromSmiles("C=CCCCC")
# Label each atom starting from 1
for atom in hexene.GetAtoms():
atom.SetAtomMapNum(atom.GetIdx() + 1)
# Visualize the molecule with atom numbers
Draw.MolToImage(hexene, size=(300, 300))
Figure 5: Structure of Hexene