I'm trying to plot two boxes using pgfplots. However, the tick labels are overlapping with the plot itself, which is quite annoying:
Ideally I want them so that, e.g. k_2^- is on the top of the red box and k_2^- + \epsilon_2 is on top of the green box. Similarly for the other two xlabels.
The source code is below:
\documentclass[border=1pt, 11pt]{standalone}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{pgfplots}
\pgfplotsset{compat=1.9}
\usepackage{tikz}
\usetikzlibrary{decorations.text}
\usetikzlibrary{arrows, decorations.markings}
\usetikzlibrary[shapes,arrows.meta,bending,shapes.geometric]
\begin{document}
\LARGE
\begin{tikzpicture}
\makeatletter
\tikzset{
nomorepostaction/.code=\makeatletter\let\tikz@postactions\pgfutil@empty, % From https://tex.stackexchange.com/questions/3184/applying-a-postaction-to-every-path-in-tikz/5354#5354
my axis/.style={
postaction={
decoration={
markings,
mark=at position 1 with {
% \arrow[ultra thick]{latex}
}
},
decorate,
nomorepostaction
},
semithick,
->,
shorten >=0pt,
>={Stealth[round]},
every path/.append style=my axis % this is necessary so it works both with "axis lines=left" and "axis lines=middle"
}
}
\makeatother
\begin{axis}[
axis lines = center,
axis line style = my axis,
xmin=-1,
xmax=1,
ymin=-0.8,
ymax=0.8,
xlabel = \(x\),
xlabel style={xshift=1.5em, yshift=-.75em},
ylabel = \(y\),
ylabel style={rotate=0, xshift=0.25em, yshift=0.25em},
xtick={ 0, 1/2.2, 1/2+0.4},
xticklabels={ 0, $k_1^-$, $k_1^-+\epsilon_1$},
ytick={ 1/2.5, 2/3},
yticklabels={ $k_2^-$, $k_2^- + \epsilon_2$},
xticklabel pos=left,
yticklabel pos=left,
width=10cm, height=11cm,
semithick,
axis on top
]
\addplot[sharp plot, draw=green, fill=green!20!white,
semithick] coordinates
{(-1/2-0.4, 2/3)
(1/2+0.4, 2/3)
(1/2+0.4, - 2/3)
(-1/2-0.4,- 2/3)
(-1/2-0.4, 2/3)};
% \closedcycle;
\addplot[sharp plot, draw=magenta, fill=magenta!20!white, semithick] coordinates
{(-1/2.2, 1/2.5)
(1/2.2, 1/2.5)
(1/2.2, -1/2.5)
(-1/2.2,-1/2.5)
(-1/2.2, 1/2.5)};
\node at (132.5, 1125) (label2) {$\mathcal{P}^-$};
\node at (175, 1375) (label2) {$\mathcal{P}^-_{\epsilon}$};
\end{axis}
\end{tikzpicture}
\end{document}
In addition, I printed the labels P and P_{\epsilon} in a hacky way (imo), since for some reason the (x,y) coordinate with the \node command is not the same as the coordinates of the plots. I've also tried using the \draw command, which also has the same problem.
I'd appreciate any help on these issues!
Best Answer
If you use a
compat
higher than1.11
, inside theaxis
environment the default coordinates will be the plot axis ones. Otherwise, you need to explicitly useaxis cs:
in\draw
or\node
commands.I removed things I think are not needed (are you sure about the
\LARGE
?) and used relative positioning instead of hard distances when possible.