Ticks with integer numbers only (instead of fractional values)

I am looking to make a scatter plot some values with x values that can only be integers (1,2,3…).

By default, Julia will sometimes use x ticks that are integers values, or sometimes as floats, depending on the range of x-values:

using Plots 

n_data = 14
x = collect(1:n_data)
y = rand(n_data)

scatter(x, y)

Taking n_data = 10, I get x ticks at (2,4,6,…) as I wish to obtain but with n_data = 14 I obtain fractional values of (2.5,5,7,5,…).

How can I force Julia to only display integers values as x ticks?

Thanks in advance!

It would be nice if you could force ints/only use the x values specified, but I don’t know of a way. This works though

scatter(x, y, xticks = x)
1 Like

One trick can be this one:

julia> x = 14*rand(20);

julia> function int_ticks(x; step=1) 
           imin = floor(Int, minimum(x))
           imax = ceil(Int, maximum(x))
           return range(imin, imax, step=step)
int_ticks (generic function with 2 methods)

julia> scatter(x, rand(20), xticks=int_ticks(x; step=2))

or, to be sure that the extrema of the ticks appear:

julia> scatter(x, rand(20), xticks=int_ticks(x; step=2), xlims=extrema(int_ticks(x)))`

Then you get:


In other words, you can set anything to be the xticks, so you can do that by hand, such as xticks=0:2:14.