Beginning and the end of GridLines

Suppose I have this plot:

Plot[Sin[x], {x, 0, 10}, GridLines -> {None, {-1/2, 0, 1/2}}]

Looks fine isn’t it?

Take a closer look at the y-ticks:

The grid line is continuing on to minus infinity (and to plus infinity too) and lays over the tick label.

The effect is not that bad in this case, it is just a gray thin line, but I want to find a way to fix it, so the grid line extends from exactly 0 to exactly 10.

The doc to GridLines says

For each direction, the following grid line options can be given:

func a function to be applied to Subscript[x, min], Subscript[x, max] to get the grid line option

I tried

Function[{min, max}, {-1, 1}][-1, 1]
(* {-1, 1} *)
Plot[Sin[x], {x, 0, 10}
 , GridLines -> {None, {{1/2, Function[{min, max}, {-1, 1}][-1, 1]}}}]

Just to see if it works at all, but I got an error message: “Encountered 1 where a directive was expected in the value of GridLines.”

I don’t understand how to use the pure function, can any one show me an example?

Thanks a lot.

The effect is not that bad in this case, it is just a gray thin line,
but I want to find a way to fix it, so the grid line extends from
exactly 0 to exactly 10.

You can set PlotRangePadding to None in the X direction:

Plot[Sin[x], {x, 0, 10}, GridLines -> {None, {-1/2, 0, 1/2}}, PlotRangePadding -> {None, Automatic}]

Thanks a lot Hans!

PlotRangePadding does solve the problem, but either way I do want to be familiar with this option to GridLines I mentioned.

I Just found out that the Function option is for specifying the positions of the lines, and not for the start and end of its length.

Looks like Epilog could be helpful.

If you are asking about the function for specifying the grid lines, some examples

Plot[Sin[x], {x, 0, 10}, GridLines -> {None, {-1, 1} &}]

Plot[Sin[x], {x, 0, 10}, GridLines -> {None, {-1, -0.75, 0.25, 1} &}]

Plot[Sin[x], {x, 0, 10}, GridLines -> {None, FindDivisions[{##}, 9] &}]

Using Epilog

xRange = {0, 10};
yRange = {-1, 1};

epilog = {Thin, Opacity[0.5], Line[{{First@range, #}, {Last@range, #}}] & /@ 
         FindDivisions[yRange, 8]};

Plot[Sin[x], {x, 0, 10}, Epilog -> epilog]

FunctionRange can be used so the y range is not hardcoded.

FunctionRange[{Sin[x], 0 <= x <= 10} , x, y]