Plot High-resolution Chemical Structures Using RDkit

It is pretty easy to converted smiles into the chemical structure using RDkit.

The code is short and straightforward:

from rdkit import Chem
from rdkit.Chem import Draw
smiles = 'CC1CCC2(C(C3C(O2)CC4C3(CCC5C4CCC6C5(CCC(C6)OC7C(C(C(C(O7)CO)OC8C(C(C(C(O8)CO)O)OC9C(C(C(CO9)O)O)O)OC2C(C(C(C(O2)CO)O)O)O)O)O)C)C)C)NC1' 
m = Chem.MolFromSmiles(smiles)
Draw.MolToImage(m)

However, I am not satisfied with the image quality. The image resolution is extremely poor.

low resolution image

After searching online, I have found several solutions. The new code supports rendering to SVG, which allows to plot high-resolution images.

Solution 1:

from rdkit import Chem
from rdkit.Chem.Draw import IPythonConsole
from rdkit.Chem import rdDepictor
from rdkit.Chem.Draw import rdMolDraw2D
from IPython.display import SVG

def moltosvg(mol, molSize = (300,300), kekulize = True):
    mc = Chem.Mol(mol.ToBinary())
    if kekulize:
        try:
            Chem.Kekulize(mc)
        except:
            mc = Chem.Mol(mol.ToBinary())
    if not mc.GetNumConformers():
        rdDepictor.Compute2DCoords(mc)
    drawer = rdMolDraw2D.MolDraw2DSVG(molSize[0],molSize[1])
    drawer.DrawMolecule(mc)
    drawer.FinishDrawing()
    svg = drawer.GetDrawingText()
    return svg.replace('svg:','')

SVG(moltosvg(m))

high resolution image

Solution 2:

from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem.Draw import rdMolDraw2D
from rdkit.Chem import rdDepictor
rdDepictor.SetPreferCoordGen(True)
from rdkit.Chem.Draw import IPythonConsole
from IPython.display import SVG
import rdkit

m = Chem.MolFromSmiles('CC1CCC2(C(C3C(O2)CC4C3(CCC5C4CCC6C5(CCC(C6)OC7C(C(C(C(O7)CO)OC8C(C(C(C(O8)CO)O)OC9C(C(C(CO9)O)O)O)OC2C(C(C(C(O2)CO)O)O)O)O)O)C)C)C)NC1')
d2d = rdMolDraw2D.MolDraw2DSVG(400,400)
d2d.DrawMolecule(m)
d2d.FinishDrawing()
SVG(d2d.GetDrawingText())

high resolution image

Note

  • The scripts were written and run in Jypyter notebook. Slight modifications may needed if you run them in other python IDEs.
Avatar
Yonghui Dong

My research interests include mass spectrometry imaging, metabolomics, chemometrics and chemical ecology.

comments powered by Disqus

Related