How can I do so the size of the customlegend box adapts to its content?
\documentclass[12pt]{article}
\usepackage{tikz}
\usepackage{pgfplots}
\pgfplotsset{compat=1.16}
\usepgfplotslibrary{fillbetween}
\usepackage{amsmath}
\usepackage{float}
\begin{document}
\begin{figure}[H]
\centering
\begin{tikzpicture}
\newenvironment{customlegend}[1][]{%
\begingroup
% inits/clears the lists (which might be populated from previous
% axes):
\csname pgfplots@init@cleared@structures\endcsname
\pgfplotsset{#1}%
}{%
% draws the legend:
\csname pgfplots@createlegend\endcsname
\endgroup
}
\def\addlegendimage{\csname pgfplots@addlegendimage\endcsname}
%%--------------------------------
\begin{axis}[
width=5cm, height=5cm,
xmin=0, xmax=1,
ymin=0, ymax=1.3,
xtick=\empty, ytick=\empty,
axis lines=middle,
x label style={at={(1,0)},right},
xlabel={$X_\mathrm{A}$}, ylabel={$-\dfrac{1}{r_\mathrm{A}}$},
restrict y to domain=0:1,
ylabel style={at={(ticklabel cs:0.75)},xshift=-1.25cm},
clip=false
]
\node[anchor=east] (zero) at (axis cs:0,0) {0};
\addplot [name path=V,red, very thick, samples=100, smooth,domain=0:1]
{ (1/3) * ((1)/(1-x)) };
\path[name path=axis] (axis cs:0,0) -- (axis cs:0.6,0);
\addplot [
thick,
color=blue,
fill=blue,
fill opacity=0.1
]
fill between[
of=V and axis,
soft clip={domain = 0:0.6},
];
\node[anchor=east] (zero) at (axis cs:0,0) {0};
\draw[dotted] (axis cs:0.6,0) --++ (0,-0.3) node[anchor=north] (Xaf) {$X_\mathrm{A,finale}$};
\end{axis}
\begin{customlegend}[
legend cell align=left,
legend entries={ $\dfrac{t}{c_\mathrm{A,0}}$ },
legend style={at={(6,3)},font=\footnotesize}]
\addlegendimage{legend image code/.code={
\node [color=white, draw, rectangle, minimum size=1.5em, fill=blue, fill opacity=0.1,anchor=15] {};}
}
\end{customlegend}
\end{tikzpicture}
\end{figure}
\end{document}
Or, is there an easier way to get the same kind of legend?


