Problem escaping 2nd dollar sign in plot title

Suppose I want a plot with the title “if you give me $2 then i will give you $1”

If i construct
str = "if you give me \$2 then i will give you \$1"
then
println(str)
returns
if you give me $2 then i will give you $1
as I’d hope and expect. But

x=1:5
y=1:5
print(x, y, title = str, label="")

produces this plot
ad

whereas omitting the second dollar sign in the title gives the expected (but not desired) output, i.e. if
str = "if you give me \$2 then i will give you 1"
then
plot(x, y, title = str, label="")
produces
ad2

Why is the second escaped dollar sign not behaving as I’d expect, and what is the solution?

A workaround is to use another unicode dollar sign:

using Plots
x = y = 1:5
str = "if you give me $2 then i will give you $1"
plot(x, y, title=str, label="", titlefont="Helvetica")
1 Like

Formatting text between 2 dollar signs ($) is LaTeX math mode. Funnily enough I never noticed normal strings do this too because I used LaTeXStrings to avoid escaping backslashes and dollar signs from the start. Maybe another preceding escaped backslash \\\$ makes LaTeX see \$ and escape it in its own way.

1 Like

@rafael.guerra, using a unicode dollar sign is a good workaround. the julia docs give :heavy_dollar_sign: as a reasonable alternative.

@benny, i see that plot with most backends does, indeed, allow LaTeX in titles and labels. and i’m sure there’s a way to backslash my way out of trouble, but i couldn’t make your suggestion work. i’ll just use the unicode symbol for now.

I think you are on to something here, the reason for this $ trouble is in the GR library (in the C library, not the wrapper). The math parsing is done in a less than optimal way. But, there is a way to disable this math parsing and to convince Plots to use it:

julia> import Plots: gr_text

julia> gr_text(x, y, s::AbstractString) =
           if (occursin('\\', s) || occursin("10^{", s)) &&
              match(r".*\$[^\$]+?\$.*", String(s)) === nothing
               GR.textext(x, y, s)
           else
               GR.textx(x, y, s, UInt32(0))
           end
gr_text (generic function with 2 methods)

After this fixup (the change is in the GR.textx line), the code in the OP:

str = "if you give me \$2 then i will give you \$1"
x=1:5
y=1:5
plot(x, y, title = str, label="")

works well.