# Changing the atom color for plotting xyz-files

Mathematica takes the standard color code for atoms when plotting an *.xyz file, but I want to customize the color for the specific atoms.

I really become desperate as I did not get it so far.

Example:

Import["ExampleData/caffeine.xyz"]


It doesn't really matter which colors are used. I just need to know how to change the default ones.

One can use the (undocumented?) option ColorRules:

Import["ExampleData/caffeine.xyz",
ColorRules -> {"H" -> Red, "C" -> Black, "N" -> Darker@Green, "O" -> White}]


Addendum: Other options may be found here: Options[GraphicsMoleculePlotDumpiMoleculePlot3D]. Note: The option ColorFunction seems to be unimplemented.

• Related: 24045. Commented Nov 12, 2014 at 17:11
• Great find! For the particular problem I can't imagine a better answer. I still do like the generality of my approach and I hope people find value in it elsewhere. Commented Nov 13, 2014 at 9:34
• @Mr.Wizard Thanks. I liked your answer so much, I nearly gave up after reading it. But I was curious how the bonds are determined, when bond data is missing in the xyz format. So I kept looking. Commented Nov 13, 2014 at 12:35

Try this:

t = Import["c:\\work\\temp\\1.xyz"];


allColors = {};
(*get all colors from Graphics3D*)
Scan[If[MatchQ[#, RGBColor[__]], AppendTo[allColors, #]] &, t,
Infinity];
allColors = DeleteDuplicates[allColors]
(*{RGBColor[0.65, 0.7, 0.7], RGBColor[0.4, 0.4, 0.4]}*)
(*replace all obtained colors with any another*)
replaceRules = MapThread[Rule, {allColors, {RGBColor[0.4, 0.4, 1], RGBColor[0.4, 1, 1]}}];
t /. replaceRules


This question is closely related to: How to change element color in Periodic Table? and my solution there works here as well. However thanks to this question I realized that it had a bug which I have now fixed.

(* please load code from linked answer *)