Search code examples
pythonmatplotliblatex

Print square root symbol


I'm looking for a way to print square root symbol without any value under it.

I'm using python's matplotlib package version 3.9.

The code that I'm using to get the symbols is this:

def text_to_rgba(s, *, dpi, **kwargs):
    # To convert a text string to an image, we can:
    # - draw it on an empty and transparent figure;
    # - save the figure to a temporary buffer using ``bbox_inches="tight",
    #   pad_inches=0`` which will pick the correct area to save;

    fig = Figure(facecolor="none", linewidth=0.1, figsize=(3,3))
    fig.text(0, 0, s, **kwargs)
    
    buf = BytesIO()
    fig.savefig(buf, dpi=dpi, format="png", bbox_inches="tight",
                    pad_inches=0.01, transparent=True)
    return buf

Whan I pass s = r'$\sqrt{}$' in text_to_rgba() I get error that it expects a value as sqrt{2}:

    raise ValueError("\n" + ParseException.explain(err, 0)) from None
ValueError:
\sqrt{}
     ^
ParseSyntaxException: Expected \sqrt{value}, found '{'  (at char 5), (line:1, col:6)

I tried sqrt(no curly braces) and also sqrt{\phanthom{0}}(suggested by chatGPT). They don't work either.

Please suggest some solutions.


Solution

  • You can give the square root command an empty space as a filler, i.e. $\sqrt{\ }.

    import matplotlib.pyplot as plt
    
    fig, ax = plt.subplots()
    ax.text(0, 0, r"$\sqrt{\ }$", ha="center", fontsize=40)
    ax.set_xlim(-0.5, 0.5)
    ax.set_ylim(-0.5, 0.5)