[Tex/LaTex] Add a horizontal line to a PGFPlot and add it to the legend

pgfplotstikz-pgf

I have a PGF Plot with some computational results from a CSV file. At the time the CSV file was generated, there was a value that was not known. That value needs to be on the plot also, however.

What I have so far is:

\begin{figure}
    \centering
    \begin{tikzpicture}
        \begin{axis} [xlabel=Iteration, ylabel=Objective]
            \addplot [mark=none, blue] table [x=it, y=C, col sep=comma] {data.csv};
            \addlegendentry{Incumbent Solution}
            \addplot [mark=none, red] table [x=it, y=C*, col sep=comma] {data.csv};
            \addlegendentry{Best Solution}
        \end{axis}
    \end{tikzpicture}
    \caption{Convergence of our simulated annealing algorithm}
    \label{fig_SA}
\end{figure}

which places two curves. Now I would like to add a straight line on the plot and an entry into the legend "Optimal Solution" corresponding to that straight line.

If it's easier, I can add this to the CSVs, but I'd prefer if I could just add it into my TeX code instead.

I saw this similar question but I don't think any of the proposed solutions support adding the data series to the legend.

Best Answer

pgfplots will plot functions by default, and the simplest case of a function is a constant value, as you have requested. Simply add \addplot[mark=none, black] {0.5}; (replace 0.5 with your constant value) and style to suit. The legend entry is added in the usual manner.

The default domain for a plotted function is [-5,5], which will change the view of your initial plot. I have restricted this by setting xmin and xmax limits in the options for the axis environment. I've also set samples=2 to lighten the computation load slightly at the recommendation of Christian Feuersänger in the comments. The default is samples=25, but we only need 2 samples to adequately represent a constant.

\documentclass{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.10}

\begin{document}
\begin{tikzpicture}
\begin{axis}[%
  xlabel=Iteration,
  ylabel=Objective,
  xmin=-0.1,xmax=1.1, % <-- added here to preserve view
]
  \addplot[mark=none, blue] coordinates {(0,0) (1,1)};
  \addlegendentry{Incumbent Solution}
  \addplot[mark=none, red] coordinates {(0,1) (1,0)};
  \addlegendentry{Best Solution}
  \addplot[mark=none, black, samples=2] {0.5};
  \addlegendentry{Constant Value}
\end{axis}
\end{tikzpicture}
\end{document}

enter image description here

Related Question