3

I have a basic line pgfplot with number of data points. I would like to change the color of line connecting this data points, from Red to Green for last three points. Here is the code.

\documentclass{article}
\usepackage{pgfplots}
\pgfplotsset{compat=newest}

\pagestyle{empty}

\begin{document}
  \begin{tikzpicture}
    \begin{axis}[
      xlabel=Cost,
      ylabel=Error]
      \addplot[color=red,mark=x] coordinates {
        (2,-2.8559703)
        (3,-3.5301677)
        (4,-4.3050655)
        (5,-5.1413136)
        (6,-6.0322865)
        (7,-6.9675052)
        (8,-7.9377747)
      };
    \end{axis}
  \end{tikzpicture}
\end{document}

Here is the current output.

basic pgfplot

And here is what I would like to achieve. (Note: Arrows are just to demonstrate the change. Also, datapoint red (x) color does not matter.)

pgfplot with different line colors

I have tried to look for the potential solution online, there is a way to change color of line progressively, but I do not want that. Also, I do not want to divide the table into two tables with different colors) Thank you in advance.

1 Answer 1

4

You can create your custom colormap that only consists of the colors you want to use and provide a function such as ifthenelse(y<=-6,1,0) to the option point meta to tell PGF where to switch the colors. This function will return 1 if the y value is below or equal -6, and 0 otherwise.

Then, you can use the shader flat corner to disable color mixing, so that every segment of the plot is only in one of the colors provided by your custom colormap.

You may finally want to override the color for the marks using explicit mark options:

\documentclass[border=10mm]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=newest}

\begin{document}
  \begin{tikzpicture}
    \begin{axis}[
        colormap={mycolortable}{
            color=(red) color=(green)
        },
        xlabel=Cost,
        ylabel=Error,
        shader=flat corner,
        point meta={ifthenelse(y<=-6,1,0)},
        mark options={draw=blue}]
        \addplot[mesh, mark=x] coordinates {
            (2,-2.8559703)
            (3,-3.5301677)
            (4,-4.3050655)
            (5,-5.1413136)
            (6,-6.0322865)
            (7,-6.9675052)
            (8,-7.9377747)
        };
    \end{axis}
  \end{tikzpicture}
\end{document}

enter image description here

3
  • This is exactly what I wanted. Thank you so much. Marked as answer. Sep 29, 2022 at 17:19
  • Can you also add a conditional that renders the y point if its value is less than -6 but greater than, say, -3?
    – tush
    Aug 27, 2023 at 14:56
  • @tush There exists no y < -6 AND > -3. But you can either nest ifthenelse() functions or use the and() function or the && or || operators. See tikz.dev/math-parsing#autosec-7662 Aug 27, 2023 at 17:09

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .