Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add specific x ticks, labels and vertical lines to a plot using Plots.jl?

Tags:

plot

julia

I am trying to add to a plot two vertical lines with the corresponding ticks and labels on the x axis to highlight important points.

I found two approaches (A and B that follows), but in the first one the new ticks/labels replace rather than append the old ones, and in the second approach the labels are printed in somehow inconsistent locations (depending on the range) and can't get them where I want them to be:

using Plots, StatPlots, DataFrames
pyplot()
df = DataFrame(a = 1:10, b = 10*rand(10), c = 10 * rand(10))
f = Plots.font("DejaVu Sans", 10)
@df df plot(:a, [:b :c], label=["serie a" "serie b"], xtickfont=f, ytickfont=f, legendfont=f, guidefont=f, titlefont=f)

A:

plot!([5,7], seriestype="vline", xticks = ([5,7],["\$\\bar \\delta \$","\$\\bar \\gamma \$"]), label="")

This show up like: screenshot of A

B:

plot!([5], seriestype="vline", label="")
annotate!(5, 0, text("\$ \\bar \\delta \$",f, :bottom, :left))
plot!([7], seriestype="vline", label="")
annotate!(7, 0, text("\$\\bar \\gamma \$",f, :top)

This show up like: screenshot of B

like image 619
Antonello Avatar asked Aug 02 '18 10:08

Antonello


1 Answers

One solution is to grab the xticks from your original plot and merge them with the xticks that you want. Below is a MWE close to your example

using Plots, DataFrames
df = DataFrame(a = 1:10, b = 10rand(10), c = 10rand(10))
plt = plot(df.a, [df.b df.c], label=["serie a" "serie b"])
old_xticks = xticks(plt[1]) # grab xticks of the 1st subplot
new_xticks = ([5, 8], ["\$\\bar \\delta\$", "\$\\bar \\gamma\$"])
vline!(new_xticks[1])
keep_indices = findall(x -> all(x .≠ new_xticks[1]), old_xticks[1])
merged_xticks = (old_xticks[1][keep_indices] ∪ new_xticks[1], old_xticks[2][keep_indices] ∪ new_xticks[2])
xticks!(merged_xticks)

and produces

enter image description here

Note that I purposefully moved your index 7 to 8 so that I had to be careful to remove the original xtick there, so that this solution is a bit more general.

Also note that ticks-getter functions like xticks were added in Plots.jl v1.13.0.

like image 158
Benoit Pasquier Avatar answered Sep 22 '22 15:09

Benoit Pasquier