0
$\begingroup$

I have a function that returns a list of 100+ elements, using Table[]. For simplification, let's assume that it's just Table[i,{i,100}]. Some elements of this list are more important for me than others, so I would like to have them colored, with the rest in usual black. In this example I'd like to have elements form 12 to 25 in red and from 89 to 95 in blue. My first guess was to use Style, but how should I specify which elements to color? Thanks for any help.

$\endgroup$
5
  • 2
    $\begingroup$ Try MapAt[Style[#,Red]&, list, 12;;25]. Maybe it could be marked as a duplicate: how to change the color of digits $\endgroup$
    – Kuba
    Feb 7, 2014 at 14:09
  • $\begingroup$ Some related questions: (17550), (31449), (40754), (8191), (31152), (31535) $\endgroup$
    – Mr.Wizard
    Feb 7, 2014 at 14:31
  • 1
    $\begingroup$ The syntax that Kuba shows, using Span in MapAt, is almost certainly the cleanest way to do this but it will only work in v9 and later. See: How to make MapAt work with Span? $\endgroup$
    – Mr.Wizard
    Feb 7, 2014 at 14:34
  • $\begingroup$ @Mr.Wizard I'm on v7 $\endgroup$
    – Wojciech
    Feb 7, 2014 at 14:34
  • $\begingroup$ @Wojciech Me too. You can use my mapAtSpan function in my answer to the last post I linked above for this. If you have any trouble please let me know. $\endgroup$
    – Mr.Wizard
    Feb 7, 2014 at 14:35

2 Answers 2

4
$\begingroup$

You may like to replace those numbers with Style[number, Color].

To color according to number value:

Range@100 /. {i_ /; 12 <= i <= 25 :> Style[i, Red], i_ /; 89 <= i <= 95 :> Style[i, Blue]}

To color according to number position:

Range@100 // MapAt[Style[#, Red] &, #, 12;;25] & // MapAt[Style[#, Blue] &, #, 89;;95] &

As mentioned in comments, this MapAt version doesn't work on v7. On v7 we could alternatively use

Range@100 // MapAt[Style[#, Red] &, #, {#} & /@ Range[12, 25]] & // 
 MapAt[Style[#, Blue] &, #, {#} & /@ Range[89, 95]] &
$\endgroup$
4
  • $\begingroup$ Thanks for the answer! However, Table[i, {i, 100}] is just a simplification, I'd like for the color to be position-dependent, not value-dependent. $\endgroup$
    – Wojciech
    Feb 7, 2014 at 14:14
  • $\begingroup$ @Wojciech: Updated according to your comment. $\endgroup$
    – Yi Wang
    Feb 7, 2014 at 14:28
  • $\begingroup$ Thanks! What if I have a nested list {{1...50},{51..100}}? $\endgroup$
    – Wojciech
    Feb 7, 2014 at 15:39
  • $\begingroup$ {Range@50, Range[51, 100]} // MapAt[Style[#, Red] &, #, {1, #} & /@ Range[12, 25]] & // MapAt[Style[#, Blue] &, #, {2, #} & /@ Range[39, 45]] & $\endgroup$
    – Yi Wang
    Feb 7, 2014 at 16:47
2
$\begingroup$
a = Table[i, {i, 100}];
b = Position[a, _?(12 <= # <= 25 &)];
c = Position[a, _?(89 <= # <= 95 &)];
d = MapAt[Style[#, Red] &, a, b];
MapAt[Style[#, Blue] &, d, c]

enter image description here

$\endgroup$

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