I would like to plot a molecule in 3D and use different colors for the same atom type in the molecule. For example, by using:

MoleculePlot3D[Molecule["NC(=O)C[C@H](C(=O)O)N"], ColorRules -> {"C" -> Black}]

all C atoms become Black. But how can I make, for example, the first C atom green, the second orange, etc?


2 Answers 2


Although I was suspecting Jason B. had an undocumented option up his sleeve, I will nevertheless post an alternative solution.

colors = {Green, Orange, Pink, Yellow};

(* Generate regular plot *)
mol = MoleculePlot3D[Molecule["NC(=O)C[C@H](C(=O)O)N"]]

(* Extract atom indices of carbons *)
ind = Flatten@Position[MoleculeValue["NC(=O)C[C@H](C(=O)O)N", "FullAtomList"], Atom["C"]]

(* Make colored spheres *)
atoms = MapThread[{#1, Sphere[#2, radius]} &, {colors, ind}]

(* Replace carbons with colored spheres *)
mol /. {{RGBColor[__], Sphere[ind, r_]} :> (atoms /. radius -> r)}

Color molecule

  • $\begingroup$ This is great! Thanks! Wonder if one can easily change Opacity[] of the spheres. I tried so, but failed. $\endgroup$
    – ogledala
    Oct 21, 2022 at 11:01
  • $\begingroup$ You can: atoms = MapThread[{#1, Opacity[.5], Sphere[#2, radius]} &, {colors, ind}];. Just a note: take a look also at @JasonB. solution in which the bonds get the appropriate colors! My solution recolors only the atoms. $\endgroup$
    – Domen
    Oct 21, 2022 at 12:39

This is underdocumented but the "ColorRules" option can take both atom indices and patterns.

 ColorRules -> {2 -> Green, "C" -> Black, "O" -> Orange, 8 -> Pink}]

enter image description here

  • $\begingroup$ Is it possible to target directly "the second carbon atom" with this approach, as the OP wants? Otherwise, one has to first extract the correct indices ... $\endgroup$
    – Domen
    Oct 19, 2022 at 19:33
  • 1
    $\begingroup$ I do not have a simple way to get that, other than something like AtomList[Molecule["caffeine"], "C", "AtomIndex"][[2]] $\endgroup$
    – Jason B.
    Oct 19, 2022 at 19:47
  • $\begingroup$ Thanks, @JasonB. Is there a way to add opacity as well? I tried x, but it did not work out. x = MoleculePlot3D[Molecule["NC(=O)C[C@H](C(=O)O)N"], ColorRules -> {2 -> {Green, Opacity[0.5]}}] $\endgroup$
    – ogledala
    Oct 21, 2022 at 22:10
  • 1
    $\begingroup$ @david1983, use Directive, for example: MoleculePlot3D[Molecule["NC(=O)C[C@H](C(=O)O)N"], ColorRules -> {2 -> Directive[Red, Opacity[.2]], "C" -> Black, "O" -> Orange, 8 -> Pink}] $\endgroup$
    – Domen
    Oct 21, 2022 at 22:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.