# Methods for producting alternating TickLabels in a Plot?

I am producing a plot with alternating TickLabels. Here is a MWE:

Plot[x, {x, 0, 4},
Ticks -> (Table[{i, If[EvenQ[i], 1, 2]}, {i, Ceiling[#1], Floor[#2]}] &)]


Is there a shorter way to achieve this effect, perhaps using keywords like Automatic?

• That looks good to me except that I would have used 1 + Mod[i, 2] instead of the If statement. – Mr.Wizard Feb 1 '15 at 9:46
• Sounds good (by the way, I can't use this particular trick in my code, because the alternating expressions are more complicated than just 1, 2). – pre-kidney Feb 1 '15 at 9:49
• Fair enough. Sorry I don't have anything better for you. – Mr.Wizard Feb 1 '15 at 9:50
• @Mr.Wizard Still no better ticks handling, bug-free grid layouts etc... I suppose it is because no one is using this when twitting the code. – Kuba Feb 1 '15 at 12:37

For the tick labels {1,2}, you can save a few key strokes using

{#, 1 + Mod[#, 2]}&/@Range[Ceiling@#, Floor@#2]&
(* or  {#, 1 + Mod[#, 2]}&/@Range[Ceiling@#, #2]&  -- thanks: @SimonWoods *)


or

Array[{#, 1 + Mod[#, 2]}&, ## & @@ Ceiling@{#2, #}]&


For arbitrary pairs of labels, you can define a tick function that takes a label list as argument:

tF[l_] := Array[{#, l[[Mod[#, 2, 1]]]} &, ## & @@ Ceiling @ {#2, #}] &;

Plot[x, {x, 0, 5.}, Ticks -> tF[{2, 1}]]


Plot[2 x, {x, 0, 4},
Ticks -> {tF[Rotate[Style[#, Red, 16], Pi/6] & /@ {"label1", "label2"}], tF[{2, 1}]}]


• You could save a few more keystrokes by omitting Floor from your first method – Simon Woods Feb 1 '15 at 13:20
• Good point; thank you @Simon. – kglr Feb 1 '15 at 20:19