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.
$\begingroup$
$\endgroup$
5
$\begingroup$
$\endgroup$
4
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]] &
-
$\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 '14 at 14:14 -
$\begingroup$ @Wojciech: Updated according to your comment. $\endgroup$ – Yi Wang Feb 7 '14 at 14:28
-
$\begingroup$ Thanks! What if I have a nested list
{{1...50},{51..100}}
? $\endgroup$ – Wojciech Feb 7 '14 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 '14 at 16:47
$\begingroup$
$\endgroup$
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]
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 '14 at 14:09Kuba
shows, usingSpan
inMapAt
, 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 '14 at 14:34mapAtSpan
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 '14 at 14:35