TransWikia.com

How to have displaystyle in pgfplots' legend?

TeX - LaTeX Asked by Rphad on June 16, 2021

I want the legend of my plot to display a fraction the same way it would be done using displaystyle. When using displaystyle, the border of the legend gets cut (see picture below). How can I proceed to nicely format my equation ?
I have tried using addlegendentryextended but it doesn’t work.

Here is a MWE :

documentclass{article}
usepackage{tikz}
usepackage{pgfplots}
pgfplotsset{compat=1.16}
begin{document}

begin{tikzpicture}
    begin{axis}[axis x line=center,
      axis y line=center,
        legend pos = north west,
        xlabel = $x$,
        ylabel = {$f(x)$},
        xmin=-5,
        xmax=5,
        ymin=-2,
        ymax=5,
    ]
    %Below the red parabola is defined
    addplot [
        samples=100,
        color=blue,
    ]
    {e^x};
    addlegendentry{$e^x$}

    %Here the blue parabloa is defined
    addplot [
        domain=-4:5,
        samples=100,
        color=red,
        ]
        {1+x};
    addlegendentry{$1+x$}

    addplot [
        domain=-3:5,
        samples=100,
        color=orange,
    ]
    {1+ x + 1/2*x^2};
    addlegendentry{$displaystyle 1+ x +frac{1}{2}x^2$} % <---- goes out of border

    end{axis}
end{tikzpicture}
end{document}

Here is the output :

enter image description here

One Answer

Update: I did some further research and found that this problem has already been solved here.


I've just faced the same problem and solved it using raisebox:

raisebox{<vertical shift>}{<content>}

The drawback of doing this is the necessity of manually tuning the <vertical shift>

So, for your problem:

documentclass{article}
usepackage{tikz}
usepackage{pgfplots}
pgfplotsset{compat=1.16}
begin{document}

begin{tikzpicture}
    begin{axis}[axis x line=center,
      axis y line=center,
        legend pos = north west,
        xlabel = $x$,
        ylabel = {$f(x)$},
        xmin=-5,
        xmax=5,
        ymin=-2,
        ymax=5,
    ]
    %Below the red parabola is defined
    addplot [
        samples=100,
        color=blue,
    ]
    {e^x};
    addlegendentry{$e^x$}

    %Here the blue parabloa is defined
    addplot [
        domain=-4:5,
        samples=100,
        color=red,
        ]
        {1+x};
    addlegendentry{$1+x$}

    addplot [
        domain=-3:5,
        samples=100,
        color=orange,
    ]
    {1+ x + 1/2*x^2};
    addlegendentry{raisebox{7pt}{$displaystyle 1+ x +frac{1}{2}x^2$}} % <---- goes out of border

    end{axis}
end{tikzpicture}
end{document}

result

Answered by Leone on June 16, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP