Edit reaction image and draw it #RDKit #memo

I often use rdkit on jupyter notebook because notebook can render molecules very conveniently. However I couldn’t find way to edit font size of reaction some days ago.

Following code is an example. Changing atom font size of MolToImage is easy but reaction image can’t apply same manner.

from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem.Draw import rdMolDraw2D
from rdkit.Chem import rdChemReactions as Reactions
from rdkit.Chem.Draw import IPythonConsole
from PIL import Image

print(Draw.DrawingOptions.atomLabelFontSize)
>12
mol = Chem.MolFromSmiles('c1ccncc1')
rxn = Reactions.ReactionFromSmarts('CC(=O)C>>CC(O)C', useSmiles=True)

Draw.MolToImage(mol)
Draw.ReactionToImage(rxn)
Image from default settings

OK, next tried to change font size.


Draw.DrawingOptions.atomLabelFontSize = 30
print(Draw.DrawingOptions.atomLabelFontSize)

Draw.MolToImage(mol)
Draw.ReactionToImage(rxn)

mol object was drawn with changed font size but reaction object wasn’t.

rxn object was drawn with small font size

I found the answer to solve the issue. It was enable by using MolDraw2DCairo and change its settings. It is not efficient way because png file was required. But I could not find any other solution now.

drawer = rdMolDraw2D.MolDraw2DCairo(800, 200)
drawer.DrawReaction(rxn)
drawer.FinishDrawing()
drawer.WriteDrawingText('test.png')
im = Image.open('test.png')
im


drawer = rdMolDraw2D.MolDraw2DCairo(800, 200)
drawer.SetFontSize(1.0)
drawer.DrawReaction(rxn)
drawer.FinishDrawing()
drawer.WriteDrawingText('test2.png')
im = Image.open('test2.png')
im

As you see, atom font size was changed. ;)

Today’s code was uploaded to my gist.

Any advice will be great fully appreciated. Have a nice weekend!!!

Update

Greg showed me how to render PNG image without drawing temporal file.
Thanks so much!

I have some idea to using the method. I’ll post it after tried it.