Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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*\[Pi]}, 
  GridLines -> {2*\[Pi]*# & /@ 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*\[Pi]*# & /@ Range[n] to generate equidistant grid lines. Does Mathematica provide anything simpler?

share|improve this question
You could also use Array[2 \[Pi] #, n]. –  Pickett Jan 26 at 10:52
@Pickett you forgot a &, but yes. –  Mr.Wizard Jan 26 at 11:36
add comment

3 Answers

up vote 4 down vote accepted

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.

share|improve this answer
add comment

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

share|improve this answer
add comment

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

share|improve this answer
add comment

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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