2
$\begingroup$

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?

$\endgroup$
  • 1
    $\begingroup$ That looks good to me except that I would have used 1 + Mod[i, 2] instead of the If statement. $\endgroup$ – Mr.Wizard Feb 1 '15 at 9:46
  • $\begingroup$ 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). $\endgroup$ – pre-kidney Feb 1 '15 at 9:49
  • $\begingroup$ Fair enough. Sorry I don't have anything better for you. $\endgroup$ – Mr.Wizard Feb 1 '15 at 9:50
  • 2
    $\begingroup$ @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. $\endgroup$ – Kuba Feb 1 '15 at 12:37
5
$\begingroup$

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}]]

enter image description here

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

enter image description here

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

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.