Argument for number of axis ticks

Is there a keyword argument to tune the number of ticks?
How could this be done?
I usually use Plots with the GR backend.

Often the routine finds a good number for the ticks.
Sometimes, I’d like to tune it a bit, e.g. here:
Screen Shot 2022-02-20 at 2.48.03 PM

I am not sure how to touch this.
It would be great if there would be a way to extend the implementation for ticks and not just overwrite everything brute force as with:

ticks = collect(0:0.2:1)
ticklabels = [ @sprintf("%5.1f",x) for x in ticks ]
plot(xticks=(ticks,ticklabels))

Two things:

  1. It would be great if the number of ticks could take the length of the numbers into account. This implies knowledge of the font size and length of the axis as well as the number range to be ticked.
  2. A quick fix would be a semi manual argument like plot(..., xticks = :fewer)

Things that might relate:
Number of digits in xticks for Plots.jl
time tick issus on x axis

1 Like

There are a number of knobs to turn in Plots.jl. For instance, you could use the argument formatter and an adequate font size:

using Formatting, Plots; gr()
x = -6:0.01:6
plot(x, sin, formatter = x -> format(x, precision=2), tickfontsize=10)

NB: there are also individual xformatter and yformatter

3 Likes

Thanks, using Formatting was new to me!

I run in to this a lot: many of my axes have too many y ticks on them (>6). Would love to have an axis option to set the number of ticks, usually to 4 or 5 instead.

I often end up simply halving the number with a line like below, but this doesn’t always keep the tick for 0.

p = plot(...)
plot!(p[2], yticks=yticks(p[2])[1][1:2:end])

Cheers.

Note that the plot() keyword xrot rotates the labels and alleviates this problem.

Regarding your workaround:

You could define a helper function to take care of decimating the x- or y-axis labels.
For example:

function decimate_ticks(p, axis)
    zt = axis == :x ? only(xticks(p)) : only(yticks(p))
    n, k = length(zt[1]), findfirst(≈(0), zt[1])
    ix = isnothing(k) ? (1:2:n) : sort([k:-2:1; (k+2):2:n])
    return (zt[1][ix], zt[2][ix])
end

x = -8:9
p = plot(x, x .^4)
plot!(p, xticks=decimate_ticks(p, :x), yticks=decimate_ticks(p,:y))
1 Like