2
$\begingroup$

I have a set of data with coordinate and a weight which I map with colours. I want a particular colour to appear on the top of others. For example

c[1] = Blue; c[2] = Red; c[3] = Green;
d1 = {RandomChoice[{1, 2, 3}], RandomReal[1, 2]} & /@ Range[20];
d2 = {RandomChoice[{1, 2, 3}], RandomReal[1, 2]} & /@ Range[20];
Graphics[{{c[#[[1]]], Disk[#[[2]], 0.1]} & /@ d1,
          {c[#[[1]]], Disk[#[[2]], 0.1]} & /@ d2}]

enter image description here

Now I want all the red points to appear on the top layer. Manually I can double-click on each of them and use Move to Front option.

enter image description here enter image description here

Is it possible to do it with a command?

$\endgroup$
  • 1
    $\begingroup$ They are rendered in the order that they appear inside of Graphics. $\endgroup$ – Szabolcs Sep 13 '17 at 13:16
  • 2
    $\begingroup$ FrontEndExecute[FrontEndToken["MoveToFront"]] works. To test the code you can evaluate Button["x",FrontEndExecute[FrontEndToken["MoveToFront"]] ], select the disk, and click on the button. $\endgroup$ – andre314 Sep 13 '17 at 13:39
0
$\begingroup$

Assuming your Graphics is saved in a variable g:

c[1] = Blue; c[2] = Red; c[3] = Green;
d1 = {RandomChoice[{1, 2, 3}], RandomReal[1, 2]} & /@ Range[20];
d2 = {RandomChoice[{1, 2, 3}], RandomReal[1, 2]} & /@ Range[20];
g = Graphics[{{c[#[[1]]], Disk[#[[2]], 0.1]} & /@ d1,
          {c[#[[1]]], Disk[#[[2]], 0.1]} & /@ d2}]

graphics

Here is one simple way:

ReplacePart[g, 1 :> SortBy[Flatten[g[[1]], 1], First]]

graphics

A drawback of this approach is that it reorders all the disks, not just puts red disks forward. The following approach only does the latter without reordering:

ReplacePart[g, 
 1 :> {Cases[g[[1]], {Except@Red, _Disk}, -3], Cases[g[[1]], {Red, _Disk}, -3]}]

graphics

$\endgroup$
0
$\begingroup$

I think the question is (at least partially) answered in a comment by @andre. (That is, use FrontEndExecute[FrontEndToken["MoveToFront"] on selected objects.)

An alternative way, following Alexey's approach, to move primitives with selected color to the front without changing the order of other primitives is to use Pick:

moveToFront[g_, color_: Red] := 
 Module[{prims = Join @@ g[[1]]}, 
  Graphics[Join @@ Pick[prims, #[[1]] === color & /@ prims, #] & /@ {False, True}]]

moveToFront[gr]

enter image description here

moveToFront[gr, Green]

enter image description here

where gr = Graphics[{{c[#[[1]]], Disk[#[[2]], 0.1]} & /@ d1, {c[#[[1]]], Disk[#[[2]], 0.1]} & /@ d2}].

$\endgroup$
  • $\begingroup$ Of course, you would need more elaborate selection function in the second argument of Pick for cases where the graphics directives and primitives are organized in arbitrary ways. $\endgroup$ – kglr Sep 13 '17 at 14:43

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.