Plots.jl - Strings as xticks

I want to replace the xticks with strings. How can I do that? When I run :

using Plots

xticks = ["$i" for i in 1:10]
plot(rand(10), xticks=xticks)

I get an error:

Julia Client – Internal Error
MethodError: no method matching isless(::Float64, ::String)
Closest candidates are:
  isless(::Float64, !Matched::Float64) at float.jl:459
  isless(!Matched::Missing, ::Any) at missing.jl:70
  isless(::AbstractFloat, !Matched::AbstractFloat) at operators.jl:148
<(::Float64, ::String) at operators.jl:260
<=(::Float64, ::String) at operators.jl:309
(::getfield(Plots, Symbol("##110#111")){Float64,Float64})(::String) at axes.jl:207
mapfilter(::getfield(Plots, Symbol("##110#111")){Float64,Float64}, ::typeof(push!), ::Array{String,1}, ::Array{String,1}) at abstractset.jl:340
filter(::Function, ::Array{String,1}) at array.jl:2351
optimal_ticks_and_labels(::Plots.Axis, ::Array{String,1}) at axes.jl:207
get_ticks(::Plots.Axis) at axes.jl:272
axis_drawing_info(::Plots.Subplot{Plots.GRBackend}) at axes.jl:591
_update_min_padding!(::Plots.Subplot{Plots.GRBackend}) at gr.jl:584
iterate at generator.jl:47 [inlined]
_collect(::Array{AbstractLayout,2}, ::Base.Generator{Array{AbstractLayout,2},typeof(Plots._update_min_padding!)}, ::Base.EltypeUnknown, ::Base.HasShape{2}) at array.jl:619
collect_similar at array.jl:548 [inlined]
map at abstractarray.jl:2018 [inlined]
1 Like

Try xticks = (1:10, xticks). Not at a computer to confirm, but I’m 80% sure that’s it. It does live in the docs somewhere, I’ve gone looking for it on numerous occasions.


This is correct - plot(rand(10), xticks = (1:10, string.(1:10)) should do what your example was trying to do.


Thanks that works!

Thx for the tips guys, very happy to find an answer and wanted to share the automation tip to show fewer digits automatically in ticks / xticks … maybe this should become a Plots Recipe macro candidate or such so everyone doesn’t have to recreate the wheel over and over ?

**# Programming is Automation and this WORKS but ONLY MANUALLY -- xticks = ([-2π:π:2π;], ["-2\\pi", "-\\pi", "0", "+\\pi", "+2\\pi"]),**
**  # NOGO SubString(string.(-2π:π:2π)[1:3], 1:3) ),**
**  # NOGO no method matching SubString(::Array{String,1}, ::UnitRange{Int64})**
**  # **NOTE Plot Graphics TIP Below WORKS to AUTOMATICALLY show 3 Digits of Precision in xticks****
**  xticks = ( [-2π:π:2π;], parse.(Float16,string.(-2π:π:2π)[:]) ),**

I think the canonical way to do that is to use round

julia> xticks = ( [-2π:π:2π;], string.(round.(-2π:π:2π, digits=2)))
([-6.283185307179586, -3.141592653589793, 0.0, 3.141592653589793, 6.283185307179586], ["-6.28", "-3.14", "0.0", "3.14", "6.28"])