Here is a beginner's question: when creating plots with mathematica, I want the grid lines to be at multiples of a constant value. E.g. in the following plot, the vertical grid lines are at multiple of 2 $\pi$. enter image description here

This is the corresponding Mathematica code:

 Plot[Sin[x], {x, 0, n*2*π}, 
  GridLines -> {2*π*# & /@ Range[n], None}, 
  GridLinesStyle -> Dashed], {n, 1, 50, 1}]

Since equidistant grid lines are very common, I wonder if there is an easier way than to use such complicated expressions like 2*π*# & /@ Range[n] to generate equidistant grid lines. Does Mathematica provide anything simpler?

  • 1
    $\begingroup$ You could also use Array[2 \[Pi] #, n]. $\endgroup$ – C. E. Jan 26 '14 at 10:52
  • $\begingroup$ @Pickett you forgot a &, but yes. $\endgroup$ – Mr.Wizard Jan 26 '14 at 11:36

Please see case #4 in Alternatives to procedural loops and iterating over lists in Mathematica. You don't need Function and Map in 2*π*# & /@ Range[n] -- instead use the "listability" of Times and write: 2 π Range[n]. Also, while it doesn't simplify this application, in many cases it is easier to give the specification for GridLines as a function, e.g.:

 GridLines -> {2 π Range[#2] &, None}

where the arguments of the function are automatically drawn from the PlotRange of the graphic.


Since multiplication is Listable, you can simply use 2 Pi Range[n]:

  Plot[Sin[x], {x, 0, 2 n Pi}, 
  GridLines -> {2 Pi Range[n], None}, 
  GridLinesStyle -> Dashed]
  {n, 1, 50, 1}

which looks clearer


Here's a way to get equally spaced gridlines based on a parameter:

grids[n_][min_, max_] := n Range @@ ({Floor@First@#, Ceiling@Last@#} &@Quotient[#, n] &@{min, max})

Manipulate[Plot[Sin[x], {x, 0,  n },
  GridLines -> grids[Pi],
  GridLinesStyle -> Dashed],
  {n, 1, 50}]

Mathematica graphics


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy