0
$\begingroup$

I'd like to draw a set of spheres with colors assigned from a defined set. To provide an example, say I wish to draw a set of three spheres of radius 2 at the positions: {{6, 5, 10}, {1, 4, 20}, {2, 4, 15}}. I might write:

pos = {{6, 5, 10}, {1, 4, 20}, {2, 4, 15}};
Graphics3D[{Sphere[pos, 2]}]

If I define an ordered set of colors for the three spheres, e.g. SphereColors={Red,Blue,Red}, how can I use this list to color the spheres as desired using Graphics3D?

$\endgroup$
  • $\begingroup$ Then you don't use the en masse rendering; you use something like MapThread[{#1, Sphere[#2, 2]} &, {SphereColors, pos}]. $\endgroup$ – J. M. is away May 29 '13 at 5:18
2
$\begingroup$

What you can do very straightforwadly is:

pos = {{6, 5, 10}, {1, 4, 20}, {2, 4, 15}};
Graphics3D[{Red, Sphere[pos[[1]], 2], Blue, Sphere[pos[[2]], 2], 
    Green, Sphere[pos[[3]], 2]}]

but of course this is somewhat ungeneralizable. So you can make it a bit more general:

cols = {Red, Blue, Green};
Graphics3D[Table[{cols[[i]], Sphere[pos[[i]], 2]}, {i, 1, 3}]]

enter image description here

You can also do it in a more elegant manner:

Graphics3D[Thread[{cols, Sphere[#, 2] & /@ pos}]]

which gives the same result.

$\endgroup$
1
$\begingroup$

As an alternative to Thread, you can also use MapThread:

pos = {{6, 5, 10}, {1, 4, 20}, {2, 4, 15}};
cols = {Red, Green, Blue};
Graphics3D@MapThread[{#1, Sphere[#2, 2]} &, {cols, pos}]

Another way is to use Apply

Graphics3D[Apply[{#1, Sphere[#2, 2]} &, Transpose[{cols, pos}], {1}]]

or using the shorthand notation:

Graphics3D[{#1, Sphere[#2, 2]} & @@@ Transpose[{cols, pos}]]

Threading twice:

Graphics3D[Thread@{cols, Thread@Sphere[pos]}]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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