Annotations with Plots.jl and PGFPlotsX using plot!(add=..., extra_kwargs=:subplots)

Hi, I am relatively new to julia and Plots, but have a solid background with matplotlib and TikZ. I have been using Plots.jl for the last few days together with the PGFPlotX backend and I really like it. One think that I am missing is the possibility to annotate data with an arrow. So I tried to implement this myself. Basically, what I am doing is to use plot!([], add = raw"\draw[{Stealth[]-}] (1,2) to (2,3) node {Text};", extra_kwargs = :subplot), as described in[1]. This works pretty good, so I implemented a function to make this more easily and add some extra options, like bending the arrow or aligning the text:

function annotate!(ax::Plots.Subplot, text, xy, xytext; textcoords=:data, va=:default, ha=:default)
    va_ = Dict(
        :bottom => "south ",
        :top => "north ",
        :default => ""
    ha_ = Dict(
        :left => "west",
        :right => "east",
        :default => ""

    anchor = ((va !== :default) | (ha !== :default)) ? "anchor=$(va_[va])$(ha_[ha])" : ""

    if textcoords === :offsetpoints
        off = "++"
        off = ""

    code = (
        raw"\draw[thick,{Stealth[]-},bend right] (" * "$(xy[1])," * "$(xy[2])" *
        ") to $off(" * "$(xytext[1])," * "$(xytext[2])" *
        raw") node[" * anchor * "] {" *
        text * "};")

    plot!(ax, [], add=code, extra_kwargs=:subplot)

This works if I apply this function e.g. as

using Plots; pgfplotsx()

p = plot(1:5)
annotate!(p, "Test", [1,1], [2,2])

The problem is that I can only run this function once, because every time that I use it again (or any other plot command) the previous annotation is deleted. Do you have any idea of how to make the annotations persistent after different plot commands have been issued?


[1] Backends · PlotsPGFPlotsX

1 Like