[Tex/LaTex] How to change only the last xticklabel

pgfplots

I would like to set the last xticklabel to \infty. How can this be achieved without necessarily knowing the xtick value?

\documentclass{article}
\usepackage{pgfplots}
\begin{document}
  \begin{tikzpicture}
    \begin{axis}[
      xticklabel={\tick >= 24 ? $\infty$ : $\pgfmathprintnumber{\tick}$}
    ]
      \addplot+[] table {\somedata};
    \end{axis}
  \end{tikzpicture}
\end{document}

(note: the above inline conditional doesn't work at all, it's just to illustrate what I am trying to do)

Best Answer

You can assign names to the label nodes and access the last one through that. The node text can't be changed after it has been created, unfortunately, so you will have to paint over it with the changed label. Here's a new style called overwrite last x tick label that takes an optional argument to specify what the last label should be overwritten with. The style first draws a white rectangle over the old label and then puts a new node on top of that. That ensures that the old label is completely covered, even if the new label takes up less space.

\documentclass{standalone}
\usepackage{pgfplots}
\begin{document}
\pgfplotsset{
    overwrite last x tick label/.style={
        every x tick label/.append style={alias=lasttick},
        extra description/.append code={
            \fill [white] (lasttick.north west) ++(0pt,-\pgflinewidth) rectangle (lasttick.south east);         
            \node [anchor=base] at (lasttick.base) {#1};}
    },
    overwrite last x tick label/.default={$\infty$}
}

  \begin{tikzpicture}
    \begin{axis}[overwrite last x tick label]
      \addplot table [row sep=crcr]{
      0 1\\
      2 1\\
      3 2\\
      4 3\\};
    \end{axis}
  \end{tikzpicture}
\end{document}